我们从Python开源项目中,提取了以下26个代码示例,用于说明如何使用matplotlib.pylab.yticks()。
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 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 dispersion_plot(text, words, ignore_case=False, title="Lexical Dispersion Plot"): """ Generate a lexical dispersion plot. :param text: The source text :type text: list(str) or enum(str) :param words: The target words :type words: list of str :param ignore_case: flag to set if case should be ignored when searching text :type ignore_case: bool """ try: from matplotlib import pylab except ImportError: raise ValueError('The plot function requires matplotlib to be installed.' 'See http://matplotlib.org/') text = list(text) words.reverse() if ignore_case: words_to_comp = list(map(str.lower, words)) text_to_comp = list(map(str.lower, text)) else: words_to_comp = words text_to_comp = text points = [(x,y) for x in range(len(text_to_comp)) for y in range(len(words_to_comp)) if text_to_comp[x] == words_to_comp[y]] if points: x, y = list(zip(*points)) else: x = y = () pylab.plot(x, y, "b|", scalex=.1) pylab.yticks(list(range(len(words))), words, color="b") pylab.ylim(-1, len(words)) pylab.title(title) pylab.xlabel("Word Offset") pylab.show()
def malt_demo(nx=False): """ A demonstration of the result of reading a dependency version of the first sentence of the Penn Treebank. """ dg = DependencyGraph("""Pierre NNP 2 NMOD Vinken NNP 8 SUB , , 2 P 61 CD 5 NMOD years NNS 6 AMOD old JJ 2 NMOD , , 2 P will MD 0 ROOT join VB 8 VC the DT 11 NMOD board NN 9 OBJ as IN 9 VMOD a DT 15 NMOD nonexecutive JJ 15 NMOD director NN 12 PMOD Nov. NNP 9 VMOD 29 CD 16 NMOD . . 9 VMOD """) tree = dg.tree() tree.pprint() if nx: # currently doesn't work import networkx from matplotlib import pylab g = dg.nx_graph() g.info() pos = networkx.spring_layout(g, dim=1) networkx.draw_networkx_nodes(g, pos, node_size=50) # networkx.draw_networkx_edges(g, pos, edge_color='k', width=8) networkx.draw_networkx_labels(g, pos, dg.nx_labels) pylab.xticks([]) pylab.yticks([]) pylab.savefig('tree.png') pylab.show()
def imshow_(x, **kwargs): if x.ndim == 2: plt.imshow(x, interpolation="nearest", **kwargs) elif x.ndim == 1: plt.imshow(x[:,None].T, interpolation="nearest", **kwargs) plt.yticks([]) plt.axis("tight") # ------------- Data -------------
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 plotErrorVsAlph(alphaVals=np.linspace(.001, 3, 1000), beta1=0.5): exactVals = cD_exact(alphaVals, beta1) boundVals = cD_bound(alphaVals, beta1) assert np.all(exactVals >= boundVals) pylab.plot(alphaVals, exactVals - boundVals, '-', linewidth=LINEWIDTH, label='beta_1=%.2f' % (beta1)) pylab.xlim([np.min(alphaVals) - 0.1, np.max(alphaVals) + 0.1]) pylab.xticks(np.arange(np.max(alphaVals) + 1)) pylab.xlabel("alpha", fontsize=FONTSIZE) pylab.ylabel("error", fontsize=FONTSIZE) pylab.yticks(np.arange(0, 1.5, 0.5)) pylab.tick_params(axis='both', which='major', labelsize=TICKSIZE)
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')
def plot_posterior_gp(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_GP(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() 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[:, i] vin = vyn[:, 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, '', '_gp_with_control') # else: # plot_model_no_control(model_aep, '', '_gp_no_control')
def plot_prediction_gp(params_fname, fig_fname, 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] x_control = xc # x_control_test = np.flipud(x_control) x_control_test = x_control * 1.5 no_panes = 5 model_aep = aep.SGPSSM_GP(y, Dlatent, M, lik='Gaussian', prior_mean=0, prior_var=1000, x_control=x_control) model_aep.load_model(params_fname) print 'ls ', np.exp(model_aep.dyn_layer.ls) my, vy, vyn = model_aep.get_posterior_y() mxp, vxp, myp, vyp, vynp = model_aep.predict_forward(T, x_control_test) 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[:, i] vin = vyn[:, i] mip = myp[:, i] vip = vyp[:, i] vinp = vynp[:, i] plt.subplot(5, 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.fill_between(np.arange(T, 2 * T), mip + 2 * np.sqrt(vip), mip - 2 * np.sqrt(vip), color=cs[i], alpha=0.4) plt.plot(np.arange(T, 2 * T), mip, '-', color=cs[i]) plt.plot(t, yi, '--', color=cs[i]) plt.axvline(x=T, color='k', linewidth=2) plt.ylabel(labels[i]) plt.xticks([]) plt.yticks([]) plt.subplot(no_panes, 1, no_panes) plt.plot(t, x_control, '-', color='m') plt.plot(np.arange(T, 2 * T), x_control_test, '-', color='m') plt.axvline(x=T, color='k', linewidth=2) plt.ylabel('I') plt.yticks([]) plt.xlabel('t') plt.savefig(fig_fname)
def main(args): e = Eligibility(length=args.length) if args.mode == "dexp": e.efunc_ = e.efunc_double_exp elif args.mode == "rect": e.efunc_ = e.efunc_rect elif args.mode == "ramp": e.efunc_ = e.efunc_ramp elif args.mode == "exp": e.efunc_ = e.efunc_exp e.gen_efunc_table() x = np.arange(args.length) print x et = e.efunc(x) # plot and test with array argument cmstr = "ko" pl.plot(x, et, cmstr, lw=1.) if args.mode == "rect": # negative time for readability without lines pl.plot(np.arange(-5, x[0]), np.zeros(5,), cmstr, lw=1.) # pl.plot([-10, -1, x[0]], [0, 0, et[0]], cmstr, lw=1.) pl.plot([x[-1], x[0] + args.length], [et[-1], 0.], cmstr, lw=1.) pl.plot(x + args.length, np.zeros((len(et))), cmstr, lw=1.) pl.ylim((-0.005, np.max(et) * 1.1)) # pl.plot(x, et, "k-", lw=1.) # pl.yticks([]) # line at zero # pl.axhline(0., c="black") pl.xlabel("t [steps]") pl.ylabel("Eligibility") if args.plotsave: pl.gcf().set_size_inches((6, 2)) pl.gcf().savefig("eligibility_window.pdf", dpi=300, bbox_inches="tight") pl.show() # check perf: loop, test with single integer arguments import time now = time.time() for i in range(100): for j in range(args.length): e.efunc(j) print "table took:", time.time() - now now = time.time() for i in range(100): for j in range(args.length): e.efunc_(j) print "feval took:", time.time() - now
def makeFigure(**kwargs): Data, trueResp = makeDataAndTrueResp(**kwargs) kemptyVals = np.asarray([0, 1, 2, 3.]) ELBOVals = np.zeros_like(kemptyVals, dtype=np.float) PointEstELBOVals = np.zeros_like(kemptyVals, dtype=np.float) # Iterate over the number of empty states (0, 1, 2, ...) for ii, kempty in enumerate(kemptyVals): resp = makeNewRespWithEmptyStates(trueResp, kempty) PointEstELBOVals[ii] = resp2ELBO_HDPTopicModel( Data, resp, doPointEstimate=1, **kwargs) ELBOVals[ii] = resp2ELBO_HDPTopicModel(Data, resp, **kwargs) # Make largest value the one with kempty=0, to make plot look good PointEstELBOVals -= PointEstELBOVals[0] ELBOVals -= ELBOVals[0] # Rescale so that yaxis has units on order of 1, not 0.001 scale = np.max(np.abs(ELBOVals)) ELBOVals /= scale PointEstELBOVals /= scale # Set buffer-space for defining plotable area xB = 0.25 B = 0.19 # big buffer for sides where we will put text labels b = 0.01 # small buffer for other sides TICKSIZE = 30 FONTSIZE = 40 LEGENDSIZE = 30 LINEWIDTH = 4 # Plot the results figH = pylab.figure(figsize=(9.1, 6)) axH = pylab.subplot(111) axH.set_position([xB, B, (1 - xB - b), (1 - B - b)]) plotargs = dict(markersize=20, linewidth=LINEWIDTH) pylab.plot(kemptyVals, PointEstELBOVals, 'v-', label='HDP point est', color='b', markeredgecolor='b', **plotargs) pylab.plot(kemptyVals, np.zeros_like(kemptyVals), 's:', label='HDP exact', color='g', markeredgecolor='g', **plotargs) pylab.plot(kemptyVals, ELBOVals, 'o--', label='HDP surrogate', color='r', markeredgecolor='r', **plotargs) pylab.xlabel('num. empty topics', fontsize=FONTSIZE) pylab.ylabel('change in ELBO', fontsize=FONTSIZE) xB = 0.25 pylab.xlim([-xB, kemptyVals[-1] + xB]) pylab.xticks(kemptyVals) pylab.yticks([-1, 0, 1]) axH = pylab.gca() axH.tick_params(axis='both', which='major', labelsize=TICKSIZE) legH = pylab.legend(loc='upper left', prop={'size': LEGENDSIZE})