我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.gcf()。
def plot_bar_chart(label_to_value, title, x_label, y_label): """ Plots a bar chart from a dict. Args: label_to_value: A dict mapping ints or strings to numerical values (int or float). title: A string representing the title of the graph. x_label: A string representing the label for the x-axis. y_label: A string representing the label for the y-axis. """ n = len(label_to_value) labels = sorted(label_to_value.keys()) values = [label_to_value[label] for label in labels] plt.title(title) plt.xlabel(x_label) plt.ylabel(y_label) plt.bar(range(n), values, align='center') plt.xticks(range(n), labels, rotation='vertical', fontsize='7') plt.gcf().subplots_adjust(bottom=0.2) # make room for x-axis labels plt.show()
def legend(self, mappable): fig = plt.gcf() posn = self.axes.get_position() extent = self.axes.get_extent() aspect = (extent[1] - extent[0]) / (extent[3] - extent[2]) self.cb_depth = 0.02 self.cb_sep = 0.01 if aspect < 1.2: self.cbar_ax = fig.add_axes([posn.x1 + self.cb_sep, posn.y0, self.cb_depth, posn.height]) plt.colorbar(mappable, ax=self.axes, orientation='vertical', cax=self.cbar_ax) else: self.cbar_ax = fig.add_axes([posn.x0, posn.y0 - 6*self.cb_sep, posn.width, 2*self.cb_depth]) plt.colorbar(mappable, ax=self.axes, orientation='horizontal', cax=self.cbar_ax) fig.canvas.mpl_connect('resize_event', self.resize_colourbar) self.resize_colourbar(None)
def analyze(context=None, results=None): import matplotlib.pyplot as plt # Plot the portfolio and asset data. ax1 = plt.subplot(211) results.algorithm_period_return.plot(ax=ax1,color='blue',legend=u'????') ax1.set_ylabel(u'??') results.benchmark_period_return.plot(ax=ax1,color='red',legend=u'????') # Show the plot. plt.gcf().set_size_inches(18, 8) plt.show() # loading the data
def plot_hist(baseline_samples, target_samples, true_x, true_y): baseline_samples = baseline_samples.squeeze() target_samples = target_samples.squeeze() bmin, bmax = baseline_samples.min(), baseline_samples.max() ax = sns.kdeplot(baseline_samples, shade=True, color=(0.6, 0.1, 0.1, 0.2)) ax = sns.kdeplot(target_samples, shade=True, color=(0.1, 0.1, 0.6, 0.2)) ax.set_xlim(bmin, bmax) y0, y1 = ax.get_ylim() plt.plot([true_y, true_y], [0, y1 - (y1 - y0) * 0.01], linewidth=1, color='r') plt.title('Predictive' + (f' at {true_x:.2f}' if true_x is not None else '')) fig = plt.gcf() fig.set_size_inches(9, 9) # plt.tight_layout() # pad=0.4, w_pad=0.5, h_pad=1.0) name = utils.DATA_DIR.replace('/', '-') # plt.tight_layout(pad=0.6) utils.save_fig('predictive-at-point-' + name)
def main(): Q = ModelStorage.load(MODEL_NAME) Q_ = (Q - Q.mean()) / (Q.max() - Q.min()) fig, ax = plt.subplots() heatmap = ax.pcolor(Q_, cmap=plt.cm.YlOrBr, alpha=0.8) fig = plt.gcf() fig.set_size_inches(8, 8) ax.set_frame_on(False) ax.set_xticklabels([1, 2, 3, 4], minor=False) ax.grid(False) ax = plt.gca() fig.savefig('report.png')
def wrap_imshow3d(func): @wraps(func) def wrapper(*args, **kwargs): aspect = kwargs.pop('aspect', 1.) normed = kwargs.pop('normed', True) spacing = kwargs.pop('spacing', 0.05) if kwargs.get('axs') is None: fig = plt.gcf() # make square by adjusting height w, h = fig.get_size_inches() fig.set_size_inches(w, w) kwargs['axs'] = fig.add_subplot(221), fig.add_subplot(222), \ fig.add_subplot(223), fig.add_subplot(224) kwargs['axs'][3].set_visible(False) axs = func(*args, **kwargs) return adjust_imshow3d(axs, aspect, spacing, normed) return wrapper
def plot(self, df, database_name, test_name, y_label): means = df.rolling(70).mean() ax = means.plot( title=test_name, alpha=0.8, xlim=(0, means.index.max() * 1.05), ylim=(0, means.max().max() * 1.05), ) ax.set(xlabel='Amount of objects in table', ylabel=y_label) ax.xaxis.set_major_formatter( FuncFormatter(lambda v, pos: prefix_unit(v, '', -3))) if y_label in self.ticks_formatters: ax.yaxis.set_major_formatter(self.ticks_formatters[y_label]) legend = ax.legend( loc='upper center', bbox_to_anchor=(0.5, 0.0), bbox_transform=plt.gcf().transFigure, fancybox=True, shadow=True, ncol=3) plt.savefig( os.path.join(self.results_path, '%s - %s.svg' % (database_name, test_name)), bbox_extra_artists=(legend,), bbox_inches='tight', )
def save2file(nameFile, fig=plt.gcf(), fileFormat='pdf', verbosity=1, indent=0, dpi=100): """ :param fig: :param nameFile: :param fileFormat: :param verbosity: :param indent: :param dpi: :return: """ fullNameFile = nameFile + '.' + fileFormat log.cnd_msg(verbosity, 0, 'Saving to file: ' + fullNameFile, indent_depth=indent) try: fig.savefig(fullNameFile, dpi=dpi, bbox_inches='tight') status = 0 except: log.cnd_warning(verbosity, 1, str(sys.exc_info()[0])) status = -1 log.cnd_status(verbosity, 0, status)
def plot_output(self, outputneuron, inputMatrix, correctOutput, points1=None, points2=None): ''' Shows a plot which compares the desired (correct) Output with the actually output of a neuron. ''' fig = plt.gcf() fig.canvas.set_window_title('Output') net_output = self.Net.forward(inputMatrix) x = np.arange(1, len(inputMatrix)+1) y = net_output[:, outputneuron-1] z = correctOutput[:, outputneuron-1] if not(points1 is None and points2 is None): points1 = np.arange(1, len(points1)+1) plt.scatter(points1, points2, 5, color='red') plt.plot(x, y, label='ANN output') plt.plot(x, z, label='Correct output') plt.xlabel('Pattern number') plt.ylabel('Output of neuron' + str(outputneuron)) plt.legend(loc='lower left') plt.show()
def plot_gradients(self, foo=False): ''' Shows the difference between the computed gradients in the ANN modul and the numerically calculated gradients. ''' fig = plt.gcf() fig.canvas.set_window_title('Comparison of the computed gradients') numgrad, grad, qua, ok = ngc.compare_gradients(self.Net, self.inputdata_tr, self.outputdata_tr) print(qua, ok) y = numgrad-grad y2 = np.absolute(y) plt.bar(np.arange(1,len(y)+1), y) plt.grid(1) plt.xlabel('Gradient') plt.ylabel('Difference') plt.show() if foo: print('numgrad: ', numgrad) print('grad: ', grad) print('difference: ', y)
def finalize_plot(allticks,handles): plt.locator_params(axis='x', nticks=Noracles,nbins=Noracles) plt.yticks([x[0] for x in allticks], [x[1] for x in allticks]) plt.tick_params( axis='y', # changes apply to the x-axis which='both', # both major and minor ticks are affected left='off', # ticks along the bottom edge are off right='off' # ticks along the top edge are off ) if LEGEND: plt.legend([h[0] for h in handles],seriesnames, loc='upper right',borderaxespad=0., ncol=1,fontsize=10,numpoints=1) plt.gcf().tight_layout() ###################################################### # Data processing
def finalize_plot(ax,fxticks,fxlabels,fxticks2,fxlabels2): # write labels and adjust layout count = fxticks[-1]+1 set_axes(ax,fxticks,fxlabels,fxticks2,fxlabels2,count,version=LABELVERSION) plt.ylim(YLIM) for x,text in zip(headerloc,headers): ax.text(x-.5, YLIM[1], text, verticalalignment='top', horizontalalignment='left', fontsize=14,style='italic') plt.plot([x-1,x-1],[YLIM[0],YLIM[1]], color='#000000', marker=None, linestyle="--",linewidth=1) if LEGEND: plt.legend([h[0] for h in handles],seriesnames,loc='upper center',borderaxespad=0., bbox_to_anchor=(0.5,-0.4),ncol=len(handles),fontsize=14,numpoints=1) plt.gcf().tight_layout() ###################################################### # Data processing
def suptitle(t, gs=None, rect=(0, 0, 1, 0.95), **kwargs): """Add a suptitle to a figure with an embedded gridspec. rect is in figure coords (0,0) bottom left, and more specifically in (x1, y1, x2, y2) with (x1, y1) bottom left, and (x2, y2) top right see https://matplotlib.org/users/tight_layout_guide.html """ fig = plt.gcf() if gs is None: try: gs = fig.npl_gs except AttributeError: raise AttributeError("nelpy suptitle requires an embedded gridspec! Use the nelpy FigureManager.") fig.suptitle(t, **kwargs) gs.tight_layout(fig, rect=rect)
def set_figsize(width, height, fig=None): """Set the figure width and height. Parameters ---------- width : float Figure width height : float Figure height fig : figure object (default=pyplot.gcf()) """ if fig is None: fig = plt.gcf() fig.set_figwidth(width) fig.set_figheight(height)
def create_chart(self, top, others): plt.clf() sizes = [x[1] for x in top] labels = ["{} {:g}%".format(x[0], x[1]) for x in top] if len(top) >= 10: sizes = sizes + [others] labels = labels + ["Others {:g}%".format(others)] title = plt.title('User activity in the last 5000 messages') title.set_va("top") title.set_ha("left") plt.gca().axis("equal") colors = ['r', 'darkorange', 'gold', 'y', 'olivedrab', 'green', 'darkcyan', 'mediumblue', 'darkblue', 'blueviolet', 'indigo'] pie = plt.pie(sizes, colors=colors, startangle=0) plt.legend(pie[0], labels, bbox_to_anchor=(0.7, 0.5), loc="center", fontsize=10, bbox_transform=plt.gcf().transFigure) plt.subplots_adjust(left=0.0, bottom=0.1, right=0.45) image_object = BytesIO() plt.savefig(image_object, format='PNG') image_object.seek(0) return image_object
def exec_file(self): print("running {0}".format(self.filename)) plt.close('all') my_globals = {'pl': plt, 'plt': plt} exec(compile(open(self.filename, "rb").read(), self.filename, 'exec'), my_globals) fig = plt.gcf() fig.canvas.draw() pngfile = op.join(self.target_dir, self.pngfilename) thumbfile = op.join("example_thumbs", self.thumbfilename) self.html = "<img src=../%s>" % self.pngfilename fig.savefig(pngfile, dpi=75, bbox_inches="tight") cx, cy = self.thumbloc create_thumbnail(pngfile, thumbfile, cx=cx, cy=cy)
def cvglmnetPlot(cvobject, sign_lambda = 1.0, **options): sloglam = sign_lambda*scipy.log(cvobject['lambdau']) fig = plt.gcf() ax1 = plt.gca() #fig, ax1 = plt.subplots() plt.errorbar(sloglam, cvobject['cvm'], cvobject['cvsd'], \ ecolor = (0.5, 0.5, 0.5), \ **options ) plt.hold(True) plt.plot(sloglam, cvobject['cvm'], linestyle = 'dashed',\ marker = 'o', markerfacecolor = 'r') xlim1 = ax1.get_xlim() ylim1 = ax1.get_ylim() xval = sign_lambda*scipy.log(scipy.array([cvobject['lambda_min'], cvobject['lambda_min']])) plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \ linewidth = 1) if cvobject['lambda_min'] != cvobject['lambda_1se']: xval = sign_lambda*scipy.log([cvobject['lambda_1se'], cvobject['lambda_1se']]) plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \ linewidth = 1) ax2 = ax1.twiny() ax2.xaxis.tick_top() atdf = ax1.get_xticks() indat = scipy.ones(atdf.shape, dtype = scipy.integer) if sloglam[-1] >= sloglam[1]: for j in range(len(sloglam)-1, -1, -1): indat[atdf <= sloglam[j]] = j else: for j in range(len(sloglam)): indat[atdf <= sloglam[j]] = j prettydf = cvobject['nzero'][indat] ax2.set(XLim=xlim1, XTicks = atdf, XTickLabels = prettydf) ax2.grid() ax1.yaxis.grid() ax2.set_xlabel('Degrees of Freedom') # plt.plot(xlim1, [ylim1[1], ylim1[1]], 'b') # plt.plot([xlim1[1], xlim1[1]], ylim1, 'b') if sign_lambda < 0: ax1.set_xlabel('-log(Lambda)') else: ax1.set_xlabel('log(Lambda)') ax1.set_ylabel(cvobject['name']) #plt.show()
def overlapped_bar(df, show=False, width=0.9, alpha=1.0, title='', xlabel='', ylabel='', **plot_kwargs): """Like a stacked bar chart except bars on top of each other with transparency""" xlabel = xlabel or df.index.name N = len(df) M = len(df.columns) indices = np.arange(N) colors = ['steelblue', 'firebrick', 'darksage', 'goldenrod', 'gray'] * int(M / 5. + 1) for i, label, color in zip(range(M), df.columns, colors): kwargs = plot_kwargs kwargs.update({'color': color, 'label': label}) plt.bar(indices, df[label], width=width, alpha=alpha if i else 1, **kwargs) plt.xticks(indices + .5 * width, ['{}'.format(idx) for idx in df.index.values]) plt.legend() plt.title(title) plt.xlabel(xlabel) if show: plt.show() return plt.gcf()
def feature_importance(model): """ Plots XGBoost's feature importance derived from given trained model. :param model: :return: """ importance = model.get_fscore(fmap=const.graphs_path+'xgb.fmap') importance = sorted(importance.items(), key=operator.itemgetter(1)) df = pd.DataFrame(importance, columns=['feature', 'fscore']) df['fscore'] = df['fscore'] / df['fscore'].sum() plt.figure() df.plot() df.plot(kind='barh', x='feature', y='fscore', legend=False, figsize=(6, 10)) plt.title('XGBoost - poredak važnosti zna?ajki') plt.xlabel('relativna važnost') plt.gcf().savefig(const.graphs_path + 'feature_importance_xgb.png')
def plot(self, dataset, path, show=False): with PdfPages(path) as pdf: x_vals = dataset.data['T'].tolist() y_vals = dataset.data[self.symbol].tolist() plt.plot(x_vals, y_vals, 'ro', alpha=0.4, markersize=4) x_vals2 = np.linspace(min(x_vals), max(x_vals), 80) fx = np.polyval(self._coeffs, x_vals2) plt.plot(x_vals2, fx, linewidth=0.3, label='') plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 4)) plt.legend(loc=3, bbox_to_anchor=(0, 0.8)) plt.title('$%s$ vs $T$' % self.display_symbol) plt.xlabel('$T$ (K)') plt.ylabel('$%s$ (%s)' % (self.display_symbol, self.units)) fig = plt.gcf() pdf.savefig(fig) plt.close() if show: webbrowser.open_new(path)
def add_subplot_axes(ax, rect, axisbg='w'): fig = plt.gcf() box = ax.get_position() width = box.width height = box.height inax_position = ax.transAxes.transform(rect[0:2]) transFigure = fig.transFigure.inverted() infig_position = transFigure.transform(inax_position) x = infig_position[0] y = infig_position[1] width *= rect[2] height *= rect[3] # <= Typo was here subax = fig.add_axes([x,y,width,height],axisbg=axisbg) x_labelsize = subax.get_xticklabels()[0].get_size() y_labelsize = subax.get_yticklabels()[0].get_size() x_labelsize *= rect[2]**0.5 y_labelsize *= rect[3]**0.5 subax.xaxis.set_tick_params(labelsize=x_labelsize) subax.yaxis.set_tick_params(labelsize=y_labelsize) return subax # -----------------------------------------------------------------
def show_histograms(n_samples=1000): """Simulates from joint and shows histograms of simulations.""" true_ps, obs_stats = helper.load(datadir + 'observed_data.pkl') ps = np.empty([n_samples, 3]) stats = np.empty([n_samples, n_percentiles]) for i in xrange(n_samples): ps[i] = sim_prior() _, _, _, idts, _ = sim_likelihood(*ps[i]) stats[i] = calc_summary_stats(idts) # plot prior parameter histograms helper.plot_hist_marginals(ps, lims=disp_lims, gt=true_ps) plt.gcf().suptitle('p(thetas)') # plot stats histograms helper.plot_hist_marginals(stats, gt=obs_stats) plt.gcf().suptitle('p(stats)') plt.show(block=False)
def display(self,angles): """ Plots wireframe models of the Dobot and obstacles. """ arm = DobotModel.get_mesh(angles) #fig = plt.figure() fig = plt.gcf() ax = Axes3D(fig) #plt.axis('equal') for Ta in arm: ax.plot(Ta[[0,1,2,0],0],Ta[[0,1,2,0],1],Ta[[0,1,2,0],2],'b') for To in self.obstacles: ax.plot(To[[0,1,2,0],0],To[[0,1,2,0],1],To[[0,1,2,0],2],'b') r_max = DobotModel.l1 + DobotModel.l2 + DobotModel.d plt.xlim([-np.ceil(r_max/np.sqrt(2)),r_max]) plt.ylim([-r_max,r_max]) ax.set_zlim(-150, 250) ax.view_init(elev=30.0, azim=60.0) plt.show() return fig
def make_RGB_graph(dates, red, green, blue, graph_path_rgb): plt.figure(1) ax = plt.subplot() # ax.bar(dates, values, width=0.01, color='k', linewidth = 0) ax.plot(dates, red, color='red', lw=3) ax.plot(dates, green, color='green', lw=3) ax.plot(dates, blue, color='blue', lw=3) ax.xaxis_date() plt.title("Time Perod; " + str(dates[0].strftime("%b-%d %H:%M")) + " to " + str(dates[-1].strftime("%b-%d %H:%M")) + " ") plt.ylabel("Sum of pixel values") fig = plt.gcf() fig.canvas.set_window_title('Caps Data Graph') fig.autofmt_xdate() if graph_path_rgb == 'show': print("SHowing graph on screen, if possible") plt.show() else: if include_split_on_tot == False: plt.savefig(graph_path_rgb) print("Graph saved to " + str(graph_path_rgb)) else: print("RGB grpah made, going to combine with totals graph...")
def make_graph(da,ta): plt.figure(1) ax = plt.subplot() # ax.bar(da, ta, width=0.01, color='green', linewidth = 0) ax.plot(da, ta, color='darkblue', lw=3) ave = 0 for x in ta: ave = ave + x av = ave / len(ta) ta = np.array(ta) ax.fill_between(da, ta, 0,where=ta < dangercold, alpha=0.6, color='darkblue') ax.fill_between(da, ta, 0,where=ta > dangercold, alpha=0.6, color='blue') ax.fill_between(da, ta, 0,where=ta > toocold, alpha=0.6, color='green') ax.fill_between(da, ta, 0,where=ta > toohot, alpha=0.6, color='red') ax.fill_between(da, ta, 0,where=ta > dangerhot, alpha=0.6, color='darkred') ax.xaxis_date() plt.title("Time Perod; " + str(da[0].strftime("%b-%d %H:%M")) + " to " + str(da[-1].strftime("%b-%d %H:%M")) + " UTC") plt.ylabel("Temp") fig = plt.gcf() fig.canvas.set_window_title('Temperature Graph') maxh = ta fig.autofmt_xdate() #plt.show() plt.savefig(graph_path)
def make_graph(da,ta): plt.figure(1) ax = plt.subplot() # ax.bar(da, ta, width=0.01, color='k', linewidth = 0) ax.plot(da, ta, color='darkblue', lw=3) ave = 0 for x in ta: ave = ave + x av = ave / len(ta) ta = np.array(ta) ax.fill_between(da, ta, 0,where=ta < dangerlow, alpha=0.6, color='darkblue') ax.fill_between(da, ta, 0,where=ta > dangerlow, alpha=0.6, color='blue') ax.fill_between(da, ta, 0,where=ta > toolow, alpha=0.6, color='green') ax.fill_between(da, ta, 0,where=ta > toohigh, alpha=0.6, color='red') ax.fill_between(da, ta, 0,where=ta > dangerhigh, alpha=0.6, color='darkred') ax.xaxis_date() plt.title("Time Perod; " + str(da[0].strftime("%b-%d %H:%M")) + " to " + str(da[-1].strftime("%b-%d %H:%M")) + " UTC") plt.ylabel("Humidity") fig = plt.gcf() fig.canvas.set_window_title('Humidity Graph') maxh = ta fig.autofmt_xdate() #plt.show() plt.savefig(graph_path)
def plot(error_index, dataset_path): img = mpimg.imread(dataset_path) plt.imshow(img) currentAxis = plt.gca() for index in error_index: row = index // 2 column = index % 2 currentAxis.add_patch( patches.Rectangle( xy=( 47 * 9 if column == 0 else 47 * 19, row * 57 ), width=47, height=57, linewidth=1, edgecolor='r', facecolor='none' ) ) fig = plt.gcf() fig.set_size_inches(11.40, 9.42) plt.savefig("fig_result.png", bbox_inches="tight", dpi=100) plt.show()
def show_labes(image, probs, lables, true_label): gs = gridspec.GridSpec(1, 3) ax1 = plt.subplot(gs[1]) x = list(reversed(lables)) y = list(reversed(probs)) colors = ['#edf8fb', '#ccece6', '#99d8c9', '#66c2a4', '#41ae76'] # colors = ['#624ea7', 'g', 'yellow', 'k', 'maroon'] # colors=list(reversed(colors)) width = 0.4 # the width of the bars ind = np.arange(len(y)) # the x locations for the groups ax1.barh(ind, y, width, align='center', color=colors) ax1.set_yticks(ind + width / 2) ax1.set_yticklabels(x, minor=False) for i, v in enumerate(y): ax1.text(v, i, '%5.2f%%' % v, fontsize=14) plt.title('Probability Output', fontsize=20) ax2 = plt.subplot(gs[2]) ax2.axis('off') ax2.imshow(image) # fig = plt.gcf() # fig.set_size_inches(8, 6) plt.title(true_label, fontsize=20) plt.show()
def viewSOMDiagram(self, plt, somMap, somDLocations): fig, ax = plt.subplots() ax.imshow(somMap, cmap=plt.cm.gray, interpolation='nearest') ax.set_title('SOM Map') ax.set_xlabel('x') ax.set_ylabel('y') for index, (x,y) in enumerate(somDLocations): ax.text(x, y, 'd{0}'.format(index + 1), verticalalignment='center', horizontalalignment='center') ax.spines['left'].set_position(('outward', len(somMap))) ax.spines['bottom'].set_position(('outward', len(somMap))) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') self.addfig(plt.gcf())
def plot_contiguous_US_tweets(lon, lat, file_path): ''' INPUT: List of longitudes (lon), list of latitudes (lat), file path to save the plot (file_path) OUTPUT: Plot of tweets in the contiguous US. ''' map = Basemap(projection='merc', resolution = 'h', area_thresh = 10000, llcrnrlon=-140.25, # lower left corner longitude of contiguous US llcrnrlat=5.0, # lower left corner latitude of contiguous US urcrnrlon=-56.25, # upper right corner longitude of contiguous US urcrnrlat=54.75) # upper right corner latitude of contiguous US x,y = map(lon, lat) map.plot(x, y, 'bo', markersize=2, alpha=.3) map.drawcoastlines() map.drawstates() map.drawcountries() map.fillcontinents(color = '#DAF7A6', lake_color='#a7cdf2') map.drawmapboundary(fill_color='#a7cdf2') plt.gcf().set_size_inches(15,15) plt.savefig(file_path, format='png', dpi=1000)
def show_labes(image,probs,lables,true_label): gs = gridspec.GridSpec(1, 2,width_ratios=[1,1],height_ratios=[1,1]) ax1 = plt.subplot(gs[0]) x = list(reversed(lables)) y = list(reversed(probs)) colors=['#edf8fb','#b2e2e2','#66c2a4','#2ca25f','#006d2c'] #colors = ['#624ea7', 'g', 'yellow', 'k', 'maroon'] #colors=list(reversed(colors)) width = 0.4 # the width of the bars ind = np.arange(len(y)) # the x locations for the groups ax1.barh(ind, y, width, align='center', color=colors) ax1.set_yticks(ind+width/2) ax1.set_yticklabels(x, minor=False) for i, v in enumerate(y): ax1.text(v, i, '%5.2f%%' %v,fontsize=14) plt.title('Probability Output',fontsize=20) ax2 = plt.subplot(gs[1]) ax2.axis('off') ax2.imshow(image) # fig = plt.gcf() # fig.set_size_inches(8, 6) plt.title(true_label,fontsize=20) plt.show()
def test_uhf(self): import pandas.tseries.converter as conv import matplotlib.pyplot as plt fig = plt.gcf() plt.clf() fig.add_subplot(111) idx = date_range('2012-6-22 21:59:51.960928', freq='L', periods=500) df = DataFrame(np.random.randn(len(idx), 2), idx) ax = df.plot() axis = ax.get_xaxis() tlocs = axis.get_ticklocs() tlabels = axis.get_ticklabels() for loc, label in zip(tlocs, tlabels): xp = conv._from_ordinal(loc).strftime('%H:%M:%S.%f') rs = str(label.get_text()) if len(rs): self.assertEqual(xp, rs)
def test_irreg_hf(self): import matplotlib.pyplot as plt fig = plt.gcf() plt.clf() fig.add_subplot(111) idx = date_range('2012-6-22 21:59:51', freq='S', periods=100) df = DataFrame(np.random.randn(len(idx), 2), idx) irreg = df.ix[[0, 1, 3, 4]] ax = irreg.plot() diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff() sec = 1. / 24 / 60 / 60 self.assertTrue((np.fabs(diffs[1:] - [sec, sec * 2, sec]) < 1e-8).all( )) plt.clf() fig.add_subplot(111) df2 = df.copy() df2.index = df.index.asobject ax = df2.plot() diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff() self.assertTrue((np.fabs(diffs[1:] - sec) < 1e-8).all())
def just_runs(self, ngl_wdg, button=None): # Create the linked objects plt.plot(self.pos[:,0], self.pos[:,1]) iax = plt.gca() # Prepare a mouse event in the middle of the plot x, y = np.array(iax.get_window_extent()).mean(0) # Prepare event lineh = iax.axhline(iax.get_ybound()[0]) setattr(lineh, 'whatisthis', 'lineh') dot = iax.plot(self.pos[0, 0], self.pos[0, 1])[0] setattr(dot, 'whatisthis', 'dot') # Instantiate the ClickOnAxisListener and call it with the event return molpx._linkutils.ClickOnAxisListener(ngl_wdg, True, [lineh], iax, self.pos, [dot] )(MouseEvent(" ", plt.gcf().canvas, x,y, button=button, key=None, step=0, dblclick=False, guiEvent=None))
def scatter_unemployment_poverty_rplot(): """reates a rplot using the values of Poverty Rate and Unemployment Rate iterates through the database and reads all the data in the given headers and creates plots for each data point """ poverty = [(demo.loc[demo['number'] == num, "Poverty Rate"].values[0]) for num in numbers] unemployment = [(demo.loc[demo['number'] == num, "Unemployment Rate"].values[0]) for num in numbers] df["Unemployment Rate %"] = np.array([float(i.replace("%", "")) for i in unemployment]) df["Poverty Rate %"] = np.array([float(i) for i in poverty], dtype="float32") plot = rplot.RPlot(data= df, x="Poverty Rate %", y="Unemployment Rate %") plot.add(rplot.GeomScatter()) plot.add(rplot.GeomPolyFit(degree=2)) plot.add(rplot.GeomDensity2D()) plt.title("Poverty Rate vs. Unemployment Rate by Community") plot.render(plt.gcf()) ax = plt.axes() for index, row in df.iterrows(): ax.annotate(row["Community Name"], (row["Poverty Rate %"], row["Unemployment Rate %"]), size=7, color='darkslategrey') plt.show()
def plot_cloud(text): # mask, max_words = np.array(Image.open(path.join(d, "uno_mask.png"))), 200 mask, max_words = np.array(Image.open(path.join(d, "mav_mask.png"))), 300 stopwords = STOPWORDS.union(common_words) wordcloud = WordCloud(background_color="white", width=2400, height=2400, mask=mask, stopwords=stopwords, max_words=max_words).generate(text)#.recolor(color_func=grey_color_func, random_state=3) # Open a plot of the generated image. plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") # import IPython; IPython.embed() fig = plt.gcf() fig.set_size_inches(18.5, 10.5) canvas = FigureCanvas(fig) png_output = BytesIO() canvas.print_png(png_output) return png_output.getvalue()
def add_subplot_axes(ax,rect,axisbg='w'): fig = plt.gcf() box = ax.get_position() width = box.width height = box.height inax_position = ax.transAxes.transform(rect[0:2]) transFigure = fig.transFigure.inverted() infig_position = transFigure.transform(inax_position) x = infig_position[0] y = infig_position[1] width *= rect[2] height *= rect[2] subax = fig.add_axes([x,y,width,height],axisbg=axisbg) x_labelsize = subax.get_xticklabels()[0].get_size() y_labelsize = subax.get_yticklabels()[0].get_size() x_labelsize *= rect[2]**0.5 y_labelsize *= rect[3]**0.5 subax.xaxis.set_tick_params(labelsize=x_labelsize) subax.yaxis.set_tick_params(labelsize=y_labelsize) return subax
def __init__(self, outdir, data_key='episode_rewards', line_color='blue'): """ Liveplot renders a graph of either episode_rewards or episode_lengths Args: outdir (outdir): Monitor output file location used to populate the graph data_key (Optional[str]): The key in the json to graph (episode_rewards or episode_lengths). line_color (Optional[dict]): Color of the plot. """ #data_key can be set to 'episode_lengths' self.outdir = outdir self._last_data = None self.data_key = data_key self.line_color = line_color #styling options matplotlib.rcParams['toolbar'] = 'None' plt.style.use('ggplot') plt.xlabel("episodes") plt.ylabel("cumulated episode rewards") fig = plt.gcf().canvas.set_window_title('averaged_simulation_graph') matplotlib.rcParams.update({'font.size': 15})
def cmPlot(cmatrix,class_names,teamName,outName): cm_temp = cmatrix[1:,1:] #(get rid of overflow bins) plt.imshow(cm_temp,interpolation='nearest',cmap=plt.cm.Reds) plt.title("%s\nConfusion Matrix" % (teamName)) cbar=plt.colorbar() cbar.set_label("# of predictions") tick_marks = np.arange(len(class_names)) plt.xticks(tick_marks, class_names, rotation=70) plt.yticks(tick_marks, class_names) plt.tight_layout() plt.ylabel('True Category') plt.xlabel('Predicted Category') width, height = cm_temp.shape for x in range(width): for y in range(height): plt.gca().annotate(str(cm_temp[x,y]),xy=(y,x),horizontalalignment = 'center',verticalalignment='center') plt.gcf().set_size_inches((8.0,6.5)) plt.savefig("%scmClinicSub.png" % (outName)) plt.close()
def despine(fig=None, ax=None, top=True, right=True, left=False, bottom=False): """Remove the top and right spines from plot(s). fig : matplotlib figure figure to despine all axes of, default uses current figure ax : matplotlib axes specific axes object to despine top, right, left, bottom : boolean if True, remove that spine """ if fig is None and ax is None: axes = plt.gcf().axes elif fig is not None: axes = fig.axes elif ax is not None: axes = [ax] for ax_i in axes: for side in ["top", "right", "left", "bottom"]: ax_i.spines[side].set_visible(not locals()[side])
def plot_dynamics(vecs, vec2, n=5, MAX_ITER=100): """ Plot how the distances between pairs change with each n iterations of the optimization method. """ for i in xrange(MAX_ITER): if (i%n==0): plt.clf() plt.xlim([-0.01, 1.2]) plt.plot(vecs[i], vec2, 'ro', color='blue') plt.grid() display.clear_output(wait=True) display.display(plt.gcf()) plt.clf() fig, ax = plt.subplots(1, 2, figsize=(13, 4)) for i in xrange(2): ax[i].set_xlim([-0.01, 1.2]) ax[i].plot(vecs[-i], vec2, 'ro', color='blue') ax[i].set_title(str(i*MAX_ITER)+' iterations') ax[i].set_xlabel('Cosine distance', fontsize=14) ax[i].set_ylabel('Assesor grade', fontsize=14) ax[i].grid()
def select_subplot(name, fig=None, layout=None, **subplot_args): """ Set the current axes. If "name" has been defined, just return that axes, otherwise make a new one. :param name: The name of the subplot :param fig: The figure, or None to select current figure :param layout: 'h' for horizontal layout, 'v' for vertical layout, 'g' for approximately-square grid :return: An axes object """ if fig is None: fig = plt.gcf() if name in _subplots and fig is _subplots[name].get_figure(): # (subplot has been created) and (figure containing it has not been closed) plt.subplot(_subplots[name]) else: if name is None: name = next(_plot_name_generator) _subplots[name] = _create_subplot(fig=fig, layout=layout, **subplot_args) return _subplots[name]
def __init__(self, *args, **kwargs): PinchView.__init__(self,*args,**kwargs) # prevent resize from causing redraw until we r ready self.ready=threading.Lock() #self.ready.acquire() self.img_view = ui.ImageView(frame=self.bounds,flex='WH') self.add_subview(self.img_view) self.b = io.BytesIO() #store base xlim and ylim, only update when drag ends self.xlim=plt.xlim() self.ylim=plt.ylim() self.centroid=tuple(self.center) # zoom center # fast and slow dpi.. self.high_dpi=72.0 self.low_dpi=16 # set output image size to match view size. this probably should be modified to use actual device dpi and size. fonts and line width are based on pts, not pixels plt.gcf().set_size_inches(self.width/self.high_dpi,self.height/self.high_dpi) #update plot, ensuring update really happens self.update_plt(dpi=self.high_dpi, waitForLock=True) ObjCInstance(self).becomeFirstResponder()
def plot_price_with_time_contours(smoothed_prices, walking_time): map_image = sp.ndimage.imread('map.png') plt.imshow(map_image.mean(2), interpolation='nearest', cmap=plt.cm.gray) zoomed_prices = sp.ndimage.zoom(smoothed_prices, map_image.shape[1]/float(smoothed_prices.shape[0])) plt.imshow(zoomed_prices.T[::-1], alpha=0.5, interpolation='nearest', cmap=plt.cm.viridis, vmin=5.25, vmax=5.75) plt.colorbar(fraction=0.03) smoothed_times = smooth(walking_time, sigma=2) zoomed_times = sp.ndimage.zoom(smoothed_times, map_image.shape[1]/float(smoothed_prices.shape[0])) plt.contour(zoomed_times.T[::-1], cmap=plt.cm.Reds, levels=range(15, 61, 15), linewidths=3) plt.gcf().set_size_inches(36, 36) plt.savefig(os.path.join(OUTPUT_PATH, 'price_with_time_contours.png'), bbox_inches='tight')
def analyze(context=None, results=None): import matplotlib.pyplot as plt # Plot the portfolio and asset data. ax1 = plt.subplot(211) results.algorithm_period_return.plot(ax=ax1,color='blue',legend=u'????') ax1.set_ylabel(u'??') results.benchmark_period_return.plot(ax=ax1,color='red',legend=u'????') # Show the plot. plt.gcf().set_size_inches(18, 8) plt.show()
def plot_dds(dd_list,dd_names,out,approximation=10000): assert len(dd_list)==len(dd_names) rcParams['figure.figsize'] = 7,7 rcParams['font.size']= 30 rcParams['xtick.labelsize'] = 20 rcParams['ytick.labelsize'] = 20 fig, plots = plt.subplots(nrows=1, ncols=1) fig.set_size_inches(7, 7) colors=['red','blue'] for dd_idx in range(len(dd_names)): dd_name=dd_names[dd_idx] dd=list(dd_list[dd_idx].values()) x=list(dd_list[dd_idx].keys()) sorted_x=np.argsort(np.array(x)) x_plot=[] dd_plot=[] x_idx=0 while x_idx<len(x): x_plot.append(x[sorted_x[x_idx]]*approximation) dd_plot.append(dd[sorted_x[x_idx]]) x_idx+=1 plots.plot(x_plot[1:],dd_plot[1:],c=colors[dd_idx],label=dd_names[dd_idx]) plots.set_yscale('log',basey=10) plots.set_xscale('log',basex=10) plots.set_xlabel('distance (bp)') plots.set_ylabel('contact probability') plots.legend(loc=3,fontsize=20) #fig.tight_layout() adj=0.2 plt.gcf().subplots_adjust(bottom=adj) plt.gcf().subplots_adjust(left=adj) plt.savefig(out+'.png')