我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pylab.subplot()。
def plot(l, x1, x2, y, e): # Plot time_range = numpy.arange(0, l) pl.figure(1) pl.subplot(221) pl.plot(time_range, x1) pl.title("Input signal") pl.subplot(222) pl.plot(time_range, x2, c="r") pl.plot(time_range, y, c="b") pl.title("Reference signal") pl.subplot(223) pl.plot(time_range, e, c="r") pl.title("Noise") pl.xlabel("time") pl.show()
def test_augment_state(self): self.msckf.augment_state() N = self.msckf.N() self.assertTrue(self.msckf.P_cam is not None) self.assertTrue(self.msckf.P_imu_cam is not None) self.assertEqual(self.msckf.P_cam.shape, (N * 6, N * 6)) self.assertEqual(self.msckf.P_imu_cam.shape, (15, N * 6)) self.assertEqual(self.msckf.N(), 2) self.assertTrue(np.array_equal(self.msckf.cam_states[0].q_CG, self.msckf.ext_q_CI)) self.assertEqual(self.msckf.counter_frame_id, 2) # Plot matrix # debug = True debug = False if debug: ax = plt.subplot(111) ax.matshow(self.msckf.P()) plt.show()
def test_F(self): w_hat = np.array([1.0, 2.0, 3.0]) q_hat = np.array([0.0, 0.0, 0.0, 1.0]) a_hat = np.array([1.0, 2.0, 3.0]) w_G = np.array([0.1, 0.1, 0.1]) F = self.imu_state.F(w_hat, q_hat, a_hat, w_G) # -- First row -- self.assertTrue(np_equal(F[0:3, 0:3], -skew(w_hat))) self.assertTrue(np_equal(F[0:3, 3:6], -np.ones((3, 3)))) # -- Third Row -- self.assertTrue(np_equal(F[6:9, 0:3], dot(-C(q_hat).T, skew(a_hat)))) self.assertTrue(np_equal(F[6:9, 6:9], -2.0 * skew(w_G))) self.assertTrue(np_equal(F[6:9, 9:12], -C(q_hat).T)) self.assertTrue(np_equal(F[6:9, 12:15], -skewsq(w_G))) # -- Fifth Row -- self.assertTrue(np_equal(F[12:15, 6:9], np.ones((3, 3)))) # Plot matrix if self.debug: ax = plt.subplot(111) ax.matshow(F) plt.show()
def test_G(self): q_hat = np.array([0.0, 0.0, 0.0, 1.0]).reshape((4, 1)) G = self.imu_state.G(q_hat) # -- First row -- self.assertTrue(np_equal(G[0:3, 0:3], -np.ones((3, 3)))) # -- Second row -- self.assertTrue(np_equal(G[3:6, 3:6], np.ones((3, 3)))) # -- Third row -- self.assertTrue(np_equal(G[6:9, 6:9], -C(q_hat).T)) # -- Fourth row -- self.assertTrue(np_equal(G[9:12, 9:12], np.ones((3, 3)))) # Plot matrix if self.debug: ax = plt.subplot(111) ax.matshow(G) plt.show()
def test_J(self): # Setup cam_q_CI = np.array([0.0, 0.0, 0.0, 1.0]) cam_p_IC = np.array([1.0, 1.0, 1.0]) q_hat_IG = np.array([0.0, 0.0, 0.0, 1.0]) N = 1 J = self.imu_state.J(cam_q_CI, cam_p_IC, q_hat_IG, N) # Assert C_CI = C(cam_q_CI) C_IG = C(q_hat_IG) # -- First row -- self.assertTrue(np_equal(J[0:3, 0:3], C_CI)) # -- Second row -- self.assertTrue(np_equal(J[3:6, 0:3], skew(dot(C_IG.T, cam_p_IC)))) # -- Third row -- self.assertTrue(np_equal(J[3:6, 12:15], I(3))) # Plot matrix if self.debug: ax = plt.subplot(111) ax.matshow(J) plt.show()
def visualize_model_init(self): """smpSHL.visualize_model_init Init model visualization """ self.Ridx = np.random.choice(self.modelsize, min(30, int(self.modelsize * 0.1))) self.Rhist = [] self.losshist = [] self.Whist = [] fig = make_figure() # print "fig", fig self.figs.append(fig) gs = make_gridspec(5, 1) for subplot in gs: self.figs[0].add_subplot(subplot)
def __init__(self, fig, gs, label='mean', color='black', alpha=1.0, min_itr=10): self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs) self._ax = plt.subplot(self._gs[0]) self._label = label self._color = color self._alpha = alpha self._min_itr = min_itr self._ts = np.empty((1, 0)) self._data_mean = np.empty((1, 0)) self._plots_mean = self._ax.plot([], [], '-x', markeredgewidth=1.0, color=self._color, alpha=1.0, label=self._label)[0] self._ax.set_xlim(0-0.5, self._min_itr+0.5) self._ax.set_ylim(0, 1) self._ax.minorticks_on() self._ax.legend(loc='upper right', bbox_to_anchor=(1, 1)) self._init = False self._fig.canvas.draw() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
def show_samples(y, ndim, nb=10, cmap=''): if ndim == 4: for i in range(nb**2): plt.subplot(nb, nb, i+1) plt.imshow(y[i], cmap=cmap, interpolation='none') plt.axis('off') else: x = y[0] y = y[1] plt.figure(0) for i in range(10): plt.subplot(2, 5, i+1) plt.imshow(x[i], cmap=cmap, interpolation='none') plt.axis('off') plt.figure(1) for i in range(10): plt.subplot(2, 5, i+1) plt.imshow(y[i], cmap=cmap, interpolation='none') plt.axis('off') plt.show()
def showExampleDocs(pylab=None, nrows=3, ncols=3): if pylab is None: from matplotlib import pylab Data = get_data(seed=0, nObsPerDoc=200) PRNG = np.random.RandomState(0) chosenDocs = PRNG.choice(Data.nDoc, nrows * ncols, replace=False) for ii, d in enumerate(chosenDocs): start = Data.doc_range[d] stop = Data.doc_range[d + 1] Xd = Data.X[start:stop] pylab.subplot(nrows, ncols, ii + 1) pylab.plot(Xd[:, 0], Xd[:, 1], 'k.') pylab.axis('image') pylab.xlim([-1.5, 1.5]) pylab.ylim([-1.5, 1.5]) pylab.xticks([]) pylab.yticks([]) pylab.tight_layout() # Set Toy Parameters ###########################################################
def plot_tree_data(data, indicies_x, indicies_y, model): plt.subplot(3, 1, 1) data, indicies_x, indicies_y, model = load_tree_data() data_line, = plt.plot(data, color="blue", label="data") data_indicies_line, = plt.plot( indicies_x, indicies_y, "o", color="green", label="fitness predictors" ) model_line, = plt.plot(model, color="red", label="model") plt.title("Data and Model Output") plt.legend() return data_line, data_indicies_line, model_line
def plot_tree_data(data, indicies_x, indicies_y, model, plot_indicies=False): plt.subplot(3, 1, 1) plt.plot(data, "o", color="blue", label="data") plt.plot(model, color="red", label="model") plt.ylim([-10, 10]) if plot_indicies: plt.plot( indicies_x, indicies_y, "o", color="green", label="fitness predictors" ) plt.title("Data and Model Output") plt.legend()
def plot1D_mat(a, b, M, title=''): """ Plot matrix M with the source and target 1D distribution Creates a subplot with the source distribution a on the left and target distribution b on the tot. The matrix M is shown in between. Parameters ---------- a : np.array, shape (na,) Source distribution b : np.array, shape (nb,) Target distribution M : np.array, shape (na,nb) Matrix to plot """ na, nb = M.shape gs = gridspec.GridSpec(3, 3) xa = np.arange(na) xb = np.arange(nb) ax1 = pl.subplot(gs[0, 1:]) pl.plot(xb, b, 'r', label='Target distribution') pl.yticks(()) pl.title(title) ax2 = pl.subplot(gs[1:, 0]) pl.plot(a, xa, 'b', label='Source distribution') pl.gca().invert_xaxis() pl.gca().invert_yaxis() pl.xticks(()) pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2) pl.imshow(M, interpolation='nearest') pl.axis('off') pl.xlim((0, nb)) pl.tight_layout() pl.subplots_adjust(wspace=0., hspace=0.2)
def rasta_plp_extractor(x, sr, plp_order=0, do_rasta=True): spec = log_power_spectrum_extractor(x, int(sr*0.02), int(sr*0.01), 'hamming', False) bark_filters = int(np.ceil(freq2bark(sr//2))) wts = get_fft_bark_mat(sr, int(sr*0.02), bark_filters) ''' plt.figure() plt.subplot(211) plt.imshow(wts) plt.subplot(212) plt.hold(True) for i in range(18): plt.plot(wts[i, :]) plt.show() ''' bark_spec = np.matmul(wts, spec) if do_rasta: bark_spec = np.where(bark_spec == 0.0, np.finfo(float).eps, bark_spec) log_bark_spec = np.log(bark_spec) rasta_log_bark_spec = rasta_filt(log_bark_spec) bark_spec = np.exp(rasta_log_bark_spec) post_spec = postaud(bark_spec, sr/2.) if plp_order > 0: lpcas = do_lpc(post_spec, plp_order) # lpcas = do_lpc(spec, plp_order) # just for test else: lpcas = post_spec return lpcas
def plot(l, samp, w1, w2, cor): time_range = numpy.arange(0, l) * (1.0 / samp) pl.figure(1) pl.subplot(211) pl.plot(time_range, w1) pl.subplot(212) pl.plot(time_range, w2, c="r") pl.xlabel("time") pl.figure(2) pl.plot(time_range, cor) pl.show()
def main(): sampling, maxvalue, wave_data = record.record() # Pick out two channels for our study. w1, w2 = wave_data[1:3] nframes = w1.shape[0] # Cut one channel in the tail, while the other in the head, # to guarantee same length and first delays second. cut_time_len = 0.2 # second cut_len = int(cut_time_len * sampling) wp1 = w1[:-cut_len] wp2 = w2[cut_len:] # Get their reduced (amplitude) version, and # calculate correlation. a = numpy.array(wp1, dtype=numpy.double) / maxvalue b = numpy.array(wp2, dtype=numpy.double) / maxvalue delay_time = delay.fst_delay_snd(a, b, sampling) # Plot the channels, also the correlation. time_range = numpy.arange(0, nframes - cut_len)*(1.0/sampling) # Still shows the original signal pl.figure(1) pl.subplot(211) pl.plot(time_range, wp1) pl.subplot(212) pl.plot(time_range, wp2, c="r") pl.xlabel("time") pl.show() # Print delay print("Chan 1 delay chan 2 by {0}".format(delay_time))
def main(): sampling, maxvalue, wave_data = record.record() # Pick out two channels for our study. w1, w2 = wave_data[0:2] nframes = w1.shape[0] # Pad one channel in the head, while the other in the tail, # to guarantee same length. pad_time_len = 0.01 # second pad_len = int(pad_time_len * sampling) pad_arr = numpy.zeros(pad_len) wp1 = numpy.concatenate((pad_arr, w1)) wp2 = numpy.concatenate((w2, pad_arr)) # Get their reduced (amplitude) version, and # calculate correlation. a = numpy.array(wp1, dtype=numpy.double) / maxvalue b = numpy.array(wp2, dtype=numpy.double) / maxvalue delay_time = delay.fst_delay_snd(a, b, sampling) # Plot the channels, also the correlation. time_range = numpy.arange(0, nframes + pad_len)*(1.0/sampling) # Still shows the original signal pl.figure(1) pl.subplot(211) pl.plot(time_range, wp1) pl.subplot(212) pl.plot(time_range, wp2, c="r") pl.xlabel("time") pl.show() # Print delay print("Chan 1 delay chan 2 by {0}".format(delay_time))
def plot_angular_velocities(title, angular_velocities, angular_velocities_filtered, block=True): fig = plt.figure() title_position = 1.05 fig.suptitle(title, fontsize='24') a1 = plt.subplot(1, 2, 1) a1.set_title( "Angular Velocities Before Filtering \nvx [red], vy [green], vz [blue]", y=title_position) plt.plot(angular_velocities[:, 0], c='r') plt.plot(angular_velocities[:, 1], c='g') plt.plot(angular_velocities[:, 2], c='b') a2 = plt.subplot(1, 2, 2) a2.set_title( "Angular Velocities After Filtering \nvx [red], vy [green], vz [blue]", y=title_position) plt.plot(angular_velocities_filtered[:, 0], c='r') plt.plot(angular_velocities_filtered[:, 1], c='g') plt.plot(angular_velocities_filtered[:, 2], c='b') plt.subplots_adjust(left=0.025, right=0.975, top=0.8, bottom=0.05) if plt.get_backend() == 'TkAgg': mng = plt.get_current_fig_manager() max_size = mng.window.maxsize() max_size = (max_size[0], max_size[1] * 0.45) mng.resize(*max_size) plt.show(block=block)
def threehistsx(x1,x2,x3,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',fig=1,fontsize=12,bins1=10,bins2=10,bins3=10): """ Script that pretty-plots three histograms of quantities x1, x2 and x3. Arguments: :param x1,x2,x3: arrays with data to be plotted :param x1leg, x2leg, x3leg: legends for each histogram :param fig: which plot window should I use? Example: x1=Lbol(AD), x2=Lbol(JD), x3=Lbol(EHF10) >>> threehists(x1,x2,x3,38,44,'AD','JD','EHF10','$\log L_{\\rm bol}$ (erg s$^{-1}$)') Inspired by http://www.scipy.org/Cookbook/Matplotlib/Multiple_Subplots_with_One_Axis_Label. """ pylab.rcParams.update({'font.size': fontsize}) pylab.figure(fig) pylab.clf() pylab.subplot(3,1,1) pylab.hist(x1,label=x1leg,color='b',bins=bins1) pylab.legend(loc='best',frameon=False) pylab.subplot(3,1,2) pylab.hist(x2,label=x2leg,color='r',bins=bins2) pylab.legend(loc='best',frameon=False) pylab.subplot(3,1,3) pylab.hist(x3,label=x3leg,color='y',bins=bins3) pylab.legend(loc='best',frameon=False) pylab.minorticks_on() pylab.subplots_adjust(hspace=0.15) pylab.draw() pylab.show()
def ipyplots(): """ Makes sure we have exactly the same matplotlib settings as in the IPython terminal version. Call this from IPython notebook. `Source <http://stackoverflow.com/questions/16905028/why-is-matplotlib-plot-produced-from-ipython-notebook-slightly-different-from-te)>`_. """ pylab.rcParams['figure.figsize']=(8.0,6.0) #(6.0,4.0) pylab.rcParams['font.size']=12 #10 pylab.rcParams['savefig.dpi']=100 #72 pylab.rcParams['figure.subplot.bottom']=.1 #.125
def plot_velocity(self, timestamps, vel_true, vel_est): N = vel_est.shape[1] t = timestamps[:N] vel_true = vel_true[:, :N] vel_est = vel_est[:, :N] # Figure plt.figure() plt.suptitle("Velocity") # X axis plt.subplot(311) plt.plot(t, vel_true[0, :], color="red", label="Ground_truth") plt.plot(t, vel_est[0, :], color="blue", label="Estimate") plt.title("x-axis") plt.xlabel("Date Time") plt.ylabel("ms^-1") plt.legend(loc=0) # Y axis plt.subplot(312) plt.plot(t, vel_true[1, :], color="red", label="Ground_truth") plt.plot(t, vel_est[1, :], color="blue", label="Estimate") plt.title("y-axis") plt.xlabel("Date Time") plt.ylabel("ms^-1") plt.legend(loc=0) # Z axis plt.subplot(313) plt.plot(t, vel_true[2, :], color="red", label="Ground_truth") plt.plot(t, vel_est[2, :], color="blue", label="Estimate") plt.title("z-axis") plt.xlabel("Date Time") plt.ylabel("ms^-1") plt.legend(loc=0)
def plot_attitude(self, timestamps, att_true, att_est): # Setup N = att_est.shape[1] t = timestamps[:N] att_true = att_true[:, :N] att_est = att_est[:, :N] # Figure plt.figure() plt.suptitle("Attitude") # X axis plt.subplot(311) plt.plot(t, att_true[0, :], color="red", label="Ground_truth") plt.plot(t, att_est[0, :], color="blue", label="Estimate") plt.title("x-axis") plt.legend(loc=0) plt.xlabel("Date Time") plt.ylabel("rad s^-1") # Y axis plt.subplot(312) plt.plot(t, att_true[1, :], color="red", label="Ground_truth") plt.plot(t, att_est[1, :], color="blue", label="Estimate") plt.title("y-axis") plt.legend(loc=0) plt.xlabel("Date Time") plt.ylabel("rad s^-1") # Z axis plt.subplot(313) plt.plot(t, att_true[2, :], color="red", label="Ground_truth") plt.plot(t, att_est[2, :], color="blue", label="Estimate") plt.title("z-axis") plt.legend(loc=0) plt.xlabel("Date Time") plt.ylabel("rad s^-1")
def test_P(self): self.assertEqual(self.msckf.P().shape, (21, 21)) # Plot matrix # debug = True debug = False if debug: ax = plt.subplot(111) ax.matshow(self.msckf.P()) plt.show()
def test_H(self): # Setup feature track track_id = 0 frame_id = 3 data0 = KeyPoint(np.array([0.0, 0.0]), 21) data1 = KeyPoint(np.array([0.0, 0.0]), 21) track = FeatureTrack(track_id, frame_id, data0, data1) # Setup track cam states self.msckf.augment_state() self.msckf.augment_state() self.msckf.augment_state() self.msckf.augment_state() track_cam_states = self.msckf.track_cam_states(track) # Feature position p_G_f = np.array([[1.0], [2.0], [3.0]]) # Test H_f_j, H_x_j = self.msckf.H(track, track_cam_states, p_G_f) # Assert self.assertEqual(H_f_j.shape, (4, 3)) self.assertEqual(H_x_j.shape, (4, 45)) # Plot matrix # debug = True debug = False if debug: ax = plt.subplot(211) ax.matshow(H_f_j) ax = plt.subplot(212) ax.matshow(H_x_j) plt.show()
def test_step(self): # Step a_B_history = self.dataset.a_B w_B_history = self.dataset.w_B for i in range(30): (a_B, w_B) = self.dataset.step() a_B_history = np.hstack((a_B_history, a_B)) w_B_history = np.hstack((w_B_history, w_B)) # Plot debug = False # debug = True if debug: plt.subplot(211) plt.plot(self.dataset.time_true, a_B_history[0, :], label="ax") plt.plot(self.dataset.time_true, a_B_history[1, :], label="ay") plt.plot(self.dataset.time_true, a_B_history[2, :], label="az") plt.legend(loc=0) plt.subplot(212) plt.plot(self.dataset.time_true, w_B_history[0, :], label="wx") plt.plot(self.dataset.time_true, w_B_history[1, :], label="wy") plt.plot(self.dataset.time_true, w_B_history[2, :], label="wz") plt.legend(loc=0) plt.show()
def __init__(self, fig, gs, time_window=500, labels=None, alphas=None): self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs) self._ax = plt.subplot(self._gs[0]) self._time_window = time_window self._labels = labels self._alphas = alphas self._init = False if self._labels: self.init(len(self._labels)) self._fig.canvas.draw() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
def __init__(self, fig, gs, num_plots, rows=None, cols=None): if cols is None: cols = int(np.floor(np.sqrt(num_plots))) if rows is None: rows = int(np.ceil(float(num_plots)/cols)) assert num_plots <= rows*cols, 'Too many plots to put into gridspec.' self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(8, 1, subplot_spec=gs) self._gs_legend = self._gs[0:1, 0] self._gs_plot = self._gs[1:8, 0] self._ax_legend = plt.subplot(self._gs_legend) self._ax_legend.get_xaxis().set_visible(False) self._ax_legend.get_yaxis().set_visible(False) self._gs_plots = gridspec.GridSpecFromSubplotSpec(rows, cols, subplot_spec=self._gs_plot) self._axarr = [plt.subplot(self._gs_plots[i], projection='3d') for i in range(num_plots)] self._lims = [None for i in range(num_plots)] self._plots = [[] for i in range(num_plots)] for ax in self._axarr: ax.tick_params(pad=0) ax.locator_params(nbins=5) for item in (ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()): item.set_fontsize(10) self._fig.canvas.draw() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
def plot_1d_model(self): plt.subplot(131) plt.plot(self.rho_bg,self.radius) plt.xlabel('density (kg/m3)') plt.ylabel('radius (km)') plt.subplot(132) plt.plot(self.vp_bg,self.radius) plt.xlabel('Vp (km/s)') plt.ylabel('radius (km)') plt.subplot(133) plt.plot(self.vs_bg,self.radius) plt.xlabel('Vs (km/s)') plt.ylabel('radius (km)') plt.show()
def gen_data2(k = 0, min_length=50, max_length=55, n_batch=5, freq = 2.): print "k", k # t = np.linspace(0, 2*np.pi, n_batch) t = np.linspace(k*n_batch, (k+1)*n_batch+1, n_batch+1, endpoint=False) # print "t.shape", t.shape, t, t[:-1], t[1:] # freq = 1. Xtmp = np.sin(t[:-1] * freq / (2*np.pi)) print Xtmp.shape # Xtmp = [np.sin(t[i:i+max_length]) for i in range(n_batch)] # print len(Xtmp) X = np.array(Xtmp).reshape((n_batch, input_size)) # X = # y = np.zeros((n_batch,)) y = np.sin(t[1:] * freq / (2 * np.pi)).reshape((n_batch, output_size)) # print X,y # print X.shape, y.shape # for i in range(batch_size): # pl.subplot(211) # pl.plot(X[i,:,0]) # # pl.subplot(312) # # pl.plot(X[i,:,1]) # pl.subplot(212) # pl.plot(y) # pl.show() return (X,y)
def plot_feat_hist(data_name_list, filename=None): if len(data_name_list) > 1: assert filename is not None pylab.figure(num=None, figsize=(8, 6)) num_rows = int(1 + (len(data_name_list) - 1) / 2) num_cols = int(1 if len(data_name_list) == 1 else 2) pylab.figure(figsize=(5 * num_cols, 4 * num_rows)) for i in range(num_rows): for j in range(num_cols): pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j) x, name = data_name_list[i * num_cols + j] pylab.title(name) pylab.xlabel('Value') pylab.ylabel('Fraction') # the histogram of the data max_val = np.max(x) if max_val <= 1.0: bins = 50 elif max_val > 50: bins = 50 else: bins = max_val n, bins, patches = pylab.hist( x, bins=bins, normed=1, alpha=0.75) pylab.grid(True) if not filename: filename = "feat_hist_%s.png" % name.replace(" ", "_") pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
def plot_feat_hist(data_name_list, filename=None): pylab.clf() num_rows = 1 + (len(data_name_list) - 1) / 2 num_cols = 1 if len(data_name_list) == 1 else 2 pylab.figure(figsize=(5 * num_cols, 4 * num_rows)) for i in range(num_rows): for j in range(num_cols): pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j) x, name = data_name_list[i * num_cols + j] pylab.title(name) pylab.xlabel('Value') pylab.ylabel('Density') # the histogram of the data max_val = np.max(x) if max_val <= 1.0: bins = 50 elif max_val > 50: bins = 50 else: bins = max_val n, bins, patches = pylab.hist( x, bins=bins, normed=1, facecolor='green', alpha=0.75) pylab.grid(True) if not filename: filename = "feat_hist_%s.png" % name pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
def fancy_show(y, cmap=''): x = y[0] y = y[1] plt.figure(0) for i in range(100): plt.subplot(10, 10, i+1) plt.imshow(x[i], cmap=cmap, interpolation='none') plt.axis('off') plt.figure(1) for i in range(100): plt.subplot(10, 10, i+1) plt.imshow(y[i], cmap=cmap, interpolation='none') plt.axis('off') plt.show()
def plot_representations(X, y, title): """Plot distributions and thier labels.""" x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) f = plt.figure(figsize=(15, 10.8), dpi=300) # ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(y[i]), color=plt.cm.Set1(y[i] / 10.), fontdict={'weight': 'bold', 'size': 9}) # if hasattr(offsetbox, 'AnnotationBbox'): # # only print thumbnails with matplotlib > 1.0 # shown_images = np.array([[1., 1.]]) # just something big # for i in range(digits.data.shape[0]): # dist = np.sum((X[i] - shown_images) ** 2, 1) # if np.min(dist) < 4e-3: # # don't show points that are too close # continue # shown_images = np.r_[shown_images, [X[i]]] # imagebox = offsetbox.AnnotationBbox( # offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), # X[i]) # ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title) return f
def plot_feat_hist(data_name_list, filename=None): if len(data_name_list)>1: assert filename is not None pylab.figure(num=None, figsize=(8, 6)) num_rows = 1 + (len(data_name_list) - 1) / 2 num_cols = 1 if len(data_name_list) == 1 else 2 pylab.figure(figsize=(5 * num_cols, 4 * num_rows)) for i in range(num_rows): for j in range(num_cols): pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j) x, name = data_name_list[i * num_cols + j] pylab.title(name) pylab.xlabel('Value') pylab.ylabel('Fraction') # the histogram of the data max_val = np.max(x) if max_val <= 1.0: bins = 50 elif max_val > 50: bins = 50 else: bins = max_val n, bins, patches = pylab.hist( x, normed=1, facecolor='blue', alpha=0.75) pylab.grid(True) if not filename: filename = "feat_hist_%s.png" % name.replace(" ", "_") pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
def plotImgPatchPrototypes(doShowNow=True): from matplotlib import pylab pylab.figure() for kk in range(K): pylab.subplot(2, 4, kk + 1) Xp = makeImgPatchPrototype(D, kk) pylab.imshow(Xp, interpolation='nearest') if doShowNow: pylab.show()
def plotTrueCovMats(doShowNow=True): from matplotlib import pylab pylab.figure() for kk in range(K): pylab.subplot(2, 4, kk + 1) pylab.imshow(Sigma[kk], interpolation='nearest') if doShowNow: pylab.show()
def _viz_Gauss(curModel, propModel, Plan, curELBO=None, propELBO=None, block=False, **kwargs): from ..viz import GaussViz from matplotlib import pylab pylab.figure() h = pylab.subplot(1, 2, 1) GaussViz.plotGauss2DFromHModel(curModel, compsToHighlight=Plan['ktarget']) h = pylab.subplot(1, 2, 2) newCompIDs = np.arange(curModel.obsModel.K, propModel.obsModel.K) GaussViz.plotGauss2DFromHModel(propModel, compsToHighlight=newCompIDs) pylab.show(block=block)
def plot_convergence_data(scores, errors): subplt_2 = plt.subplot(3, 1, 2) score_line, = plt.plot(scores, color="blue", label="score") plt.title("Best Score") plt.legend() subplt_3 = plt.subplot(3, 1, 3) error_line, = plt.plot(errors, color="red", label="error") plt.title("Best Error") plt.legend() return score_line, error_line, subplt_2, subplt_3
def plot_projections(points): num_images = len(points) plt.figure() plt.suptitle('3D to 2D Projections', fontsize=16) for i in range(num_images): plt.subplot(1, num_images, i+1) ax = plt.gca() ax.set_aspect('equal') ax.plot(points[i][0], points[i][1], 'r.')
def plot_profiles_to_file(annot, pntr, ups=200, smooth_param=50): pp = PdfPages(options.save_path + 'Figures/individual_signals.pdf') clrs_ = ['red', 'blue', 'black', 'orange', 'magenta', 'cyan'] vec_sense = {} vec_antisense = {} # for qq in tq(range(annot.shape[0])): for qq in tq(range(100)): chname = annot['chr'].iloc[qq] if annot['strand'].iloc[qq] == '+': start = annot['start'].iloc[qq] - ups stop = annot['end'].iloc[qq] for key in pntr.keys(): vec_sense[key] = pntr[key][0].get_nparray(chname, start, stop - 1) vec_antisense[key] = pntr[key][1].get_nparray(chname, start, stop - 1) xran = np.arange(start, stop) else: start = annot['start'].iloc[qq] stop = annot['end'].iloc[qq] + ups for key in pntr.keys(): vec_sense[key] = np.flipud(pntr[key][1].get_nparray(chname, start, stop)) vec_antisense[key] = np.flipud(pntr[key][0].get_nparray(chname, start, stop)) xran = np.arange(stop, start, -1) ax = {} fig = pl.figure() pl.title(annot['name'].iloc[qq]) for i, key in enumerate(pntr.keys()): sm_vec_se = sm.smooth(vec_sense[key], smooth_param)[(smooth_param - 1):-(smooth_param - 1)] sm_vec_as = sm.smooth(vec_antisense[key], smooth_param)[(smooth_param - 1):-(smooth_param - 1)] ax[key] = pl.subplot(len(pntr), 1, i+1) ax[key].plot(xran, vec_sense[key], label=key, color=clrs_[i], alpha=0.5) ax[key].plot(xran, -vec_antisense[key], color=clrs_[i], alpha=0.5) ax[key].plot(xran, sm_vec_se, color=clrs_[i], linewidth=2) ax[key].plot(xran, -sm_vec_as, color=clrs_[i], linewidth=2) ax[key].legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), fontsize=6, ncol=1) pp.savefig() pl.close() pp.close() for pn in pntr.values(): pn[0].close() pn[1].close()
def lms(x1: numpy.array, x2: numpy.array, N: int): # Verify argument shape. s1, s2 = x1.shape, x2.shape if len(s1) != 1 or len(s2) != 1 or s1[0] != s2[0]: raise Exception("Argument shape invalid, in 'lms' function") l = s1[0] # Coefficient matrix W = numpy.mat(numpy.zeros([1, 2 * N + 1])) # Coefficient (time) matrix Wt = numpy.mat(numpy.zeros([l, 2 * N + 1])) # Feedback (time) matrix y = numpy.mat(numpy.zeros([l, 1])) # Error (time) matrix e = numpy.mat(numpy.zeros([l, 1])) # Traverse channel data for i in range(N, l-N): x1_vec = numpy.asmatrix(x1[i-N:i+N+1]) y[i] = x1_vec * numpy.transpose(W) e[i] = x2[i] - y[i] W += mu * e[i] * x1_vec Wt[i] = W # Find the coefficient matrix which has max maximum. Wt_maxs = numpy.max(Wt, axis=1) row_idx = numpy.argmax(Wt_maxs) max_W = Wt[row_idx] delay_count = numpy.argmax(max_W) - N # Plot time_range = numpy.arange(0, l) pl.figure(1) pl.subplot(221) pl.plot(time_range, x1) pl.title("Input signal") pl.subplot(222) pl.plot(time_range, x2, c="r") pl.plot(time_range, y, c="b") pl.title("Reference signal") pl.subplot(223) pl.plot(time_range, e, c="r") pl.title("Noise") pl.xlabel("time") pl.figure(2) time_range2 = numpy.arange(-N, N + 1) pl.plot(time_range2, numpy.transpose(max_W)) pl.title("Maximal coefficient vector") pl.show() return delay_count
def plot_results(times_A, times_B, signal_A, signal_B, convoluted_signals, time_offset, block=True): fig = plt.figure() title_position = 1.05 matplotlib.rcParams.update({'font.size': 20}) # fig.suptitle("Time Alignment", fontsize='24') a1 = plt.subplot(1, 3, 1) a1.get_xaxis().get_major_formatter().set_useOffset(False) plt.ylabel('angular velocity norm [rad]') plt.xlabel('time [s]') a1.set_title( "Before Time Alignment", y=title_position) plt.hold("on") min_time = min(np.amin(times_A), np.amin(times_B)) times_A_zeroed = times_A - min_time times_B_zeroed = times_B - min_time plt.plot(times_A_zeroed, signal_A, c='r') plt.plot(times_B_zeroed, signal_B, c='b') times_A_shifted = times_A + time_offset a3 = plt.subplot(1, 3, 2) a3.get_xaxis().get_major_formatter().set_useOffset(False) plt.ylabel('correlation') plt.xlabel('sample idx offset') a3.set_title( "Correlation Result \n[Ideally has a single dominant peak.]", y=title_position) plt.hold("on") plt.plot(np.arange(-len(signal_A) + 1, len(signal_B)), convoluted_signals) a2 = plt.subplot(1, 3, 3) a2.get_xaxis().get_major_formatter().set_useOffset(False) plt.ylabel('angular velocity norm [rad]') plt.xlabel('time [s]') a2.set_title( "After Time Alignment", y=title_position) plt.hold("on") min_time = min(np.amin(times_A_shifted), np.amin(times_B)) times_A_shifted_zeroed = times_A_shifted - min_time times_B_zeroed = times_B - min_time plt.plot(times_A_shifted_zeroed, signal_A, c='r') plt.plot(times_B_zeroed, signal_B, c='b') plt.subplots_adjust(left=0.04, right=0.99, top=0.8, bottom=0.15) if plt.get_backend() == 'TkAgg': mng = plt.get_current_fig_manager() max_size = mng.window.maxsize() max_size = (max_size[0], max_size[1] * 0.45) mng.resize(*max_size) plt.show(block=block)
def plot_time_stamped_poses(title, time_stamped_poses_A, time_stamped_poses_B, block=True): fig = plt.figure() title_position = 1.05 fig.suptitle(title + " [A = top, B = bottom]", fontsize='24') a1 = plt.subplot(2, 2, 1) a1.set_title( "Orientation \nx [red], y [green], z [blue], w [cyan]", y=title_position) plt.plot(time_stamped_poses_A[:, 4], c='r') plt.plot(time_stamped_poses_A[:, 5], c='g') plt.plot(time_stamped_poses_A[:, 6], c='b') plt.plot(time_stamped_poses_A[:, 7], c='c') a2 = plt.subplot(2, 2, 2) a2.set_title( "Position (eye coordinate frame) \nx [red], y [green], z [blue]", y=title_position) plt.plot(time_stamped_poses_A[:, 1], c='r') plt.plot(time_stamped_poses_A[:, 2], c='g') plt.plot(time_stamped_poses_A[:, 3], c='b') a3 = plt.subplot(2, 2, 3) plt.plot(time_stamped_poses_B[:, 4], c='r') plt.plot(time_stamped_poses_B[:, 5], c='g') plt.plot(time_stamped_poses_B[:, 6], c='b') plt.plot(time_stamped_poses_B[:, 7], c='c') a4 = plt.subplot(2, 2, 4) plt.plot(time_stamped_poses_B[:, 1], c='r') plt.plot(time_stamped_poses_B[:, 2], c='g') plt.plot(time_stamped_poses_B[:, 3], c='b') plt.subplots_adjust(left=0.025, right=0.975, top=0.8, bottom=0.05) if plt.get_backend() == 'TkAgg': mng = plt.get_current_fig_manager() max_size = mng.window.maxsize() max_size = (max_size[0], max_size[1] * 0.45) mng.resize(*max_size) plt.show(block=block)
def run_regression_1D(): np.random.seed(42) print "create dataset ..." N = 50 rng = np.random.RandomState(42) X = np.sort(2 * rng.rand(N, 1) - 1, axis=0) Y = np.array([np.pi * np.sin(10 * X).ravel(), np.pi * np.cos(10 * X).ravel()]).T Y += (0.5 - rng.rand(*Y.shape)) Y = Y / np.std(Y, axis=0) def plot(model, alpha, fname): xx = np.linspace(-1.2, 1.2, 200)[:, None] if isinstance(model, IndepSGPR): mf, vf = model.predict_f(xx, alpha) else: # mf, vf = model.predict_f(xx, alpha, use_mean_only=False) mf, vf = model.predict_f(xx, alpha, use_mean_only=True) colors = ['r', 'b'] plt.figure() for i in range(model.Dout): plt.subplot(model.Dout, 1, i + 1) plt.plot(X, Y[:, i], 'x', color=colors[i], mew=2) zu = model.models[i].zu mean_u, var_u = model.models[i].predict_f(zu, alpha) plt.plot(xx, mf[:, i], '-', color=colors[i], lw=2) plt.fill_between( xx[:, 0], mf[:, i] - 2 * np.sqrt(vf[:, i]), mf[:, i] + 2 * np.sqrt(vf[:, i]), color=colors[i], alpha=0.3) # plt.errorbar(zu[:, 0], mean_u, yerr=2*np.sqrt(var_u), fmt='ro') plt.xlim(-1.2, 1.2) plt.savefig(fname) # inference print "create independent output model and optimize ..." M = N alpha = 0.01 indep_model = IndepSGPR(X, Y, M) indep_model.train(alpha=alpha) plot(indep_model, alpha, '/tmp/reg_indep_multioutput.pdf') print "create correlated output model and optimize ..." M = N ar_model = AutoSGPR(X, Y, M) ar_model.train(alpha=alpha) plot(ar_model, alpha, '/tmp/reg_autoreg_multioutput.pdf')
def plot_posterior_linear(params_fname, fig_fname, control=False, M=20): # load dataset data = np.loadtxt('./sandbox/hh_data.txt') # use the voltage and potasisum current data = data / np.std(data, axis=0) y = data[:, :4] xc = data[:, [-1]] # init hypers Dlatent = 2 Dobs = y.shape[1] T = y.shape[0] if control: x_control = xc no_panes = 5 else: x_control = None no_panes = 4 model_aep = aep.SGPSSM_Linear(y, Dlatent, M, lik='Gaussian', prior_mean=0, prior_var=1000, x_control=x_control) model_aep.load_model(params_fname) my, vy, vyn = model_aep.get_posterior_y() vy_diag = np.diagonal(vy, axis1=1, axis2=2) vyn_diag = np.diagonal(vyn, axis1=1, axis2=2) cs = ['k', 'r', 'b', 'g'] labels = ['V', 'm', 'n', 'h'] plt.figure() t = np.arange(T) for i in range(4): yi = y[:, i] mi = my[:, i] vi = vy_diag[:, i] vin = vyn_diag[:, i] plt.subplot(no_panes, 1, i + 1) plt.fill_between(t, mi + 2 * np.sqrt(vi), mi - 2 * np.sqrt(vi), color=cs[i], alpha=0.4) plt.plot(t, mi, '-', color=cs[i]) plt.plot(t, yi, '--', color=cs[i]) plt.ylabel(labels[i]) plt.xticks([]) plt.yticks([]) if control: plt.subplot(no_panes, 1, no_panes) plt.plot(t, x_control, '-', color='m') plt.ylabel('I') plt.yticks([]) plt.xlabel('t') plt.savefig(fig_fname) if control: plot_model_with_control(model_aep, '', '_linear_with_control') else: plot_model_no_control(model_aep, '', '_linear_no_control')