我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用matplotlib.pyplot.margins()。
def plot_ecdf(x, y, xlabel='attribute', legend='x'): """ Plot distribution ECDF x should be sorted, y typically from 1/len(x) to 1 TODO: function should be improved to plot multiple overlayed ecdfs """ plt.plot(x, y, marker='.', linestyle='none') # Make nice margins plt.margins(0.02) # Annotate the plot plt.legend((legend,), loc='lower right') _ = plt.xlabel(xlabel) _ = plt.ylabel('ECDF') # Display the plot plt.show()
def _show_plot(x_values, y_values, x_labels=None, y_labels=None): try: import matplotlib.pyplot as plt except ImportError: raise ImportError('The plot function requires matplotlib to be installed.' 'See http://matplotlib.org/') plt.locator_params(axis='y', nbins=3) axes = plt.axes() axes.yaxis.grid() plt.plot(x_values, y_values, 'ro', color='red') plt.ylim(ymin=-1.2, ymax=1.2) plt.tight_layout(pad=5) if x_labels: plt.xticks(x_values, x_labels, rotation='vertical') if y_labels: plt.yticks([-1, 0, 1], y_labels, rotation='horizontal') # Pad margins so that markers are not clipped by the axes plt.margins(0.2) plt.show() #//////////////////////////////////////////////////////////// #{ Parsing and conversion functions #////////////////////////////////////////////////////////////
def draw_dual_line_graph(title, x_label, y_label, y_axis_1, y_axis_2, line_1_label, line_2_label, output_path): x_axis = np.arange(0, len(y_axis_1)) fig = plt.figure() fig.suptitle(title, fontsize=14, fontweight='bold') ax = fig.add_subplot(111) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.plot(x_axis, y_axis_1, 'b') ax.plot(x_axis, y_axis_2, 'g', alpha=0.7) ax.legend([line_1_label, line_2_label], loc='center', bbox_to_anchor=(0.5, -0.18), ncol=2) ax.axis([0, np.amax(x_axis), 0, np.log(2) + .001]) plt.margins(0.2) plt.tick_params(labelsize=10) fig.subplots_adjust(bottom=0.2) plt.savefig(output_path + '.eps', format='eps') plt.savefig(output_path) plt.close(fig)
def plot(self): plt.title(self.title, y=1.01, fontsize='medium') plt.xlabel(self.xlabel) plt.ylabel(self.ylabel) plt.grid('on') plt.margins(0.1) for i in range(len(self.series_list)): x_list = [] y_list = [] for x in sorted(self.series_list[i].keys()): x_list.append(x) y_list.append(self.series_list[i][x]) #xmin, xmax = min(self.x_list), max(self.x_list) + 1 #ymin, ymax = min(self.y_list), max(self.y_list) + 1 #plt.xticks(np.arange(xmin, xmax, 1.0), np.arange(xmin, xmax, 1.0), fontsize='x-small') #plt.yticks(np.arange(ymin, ymax, 0.5), np.arange(ymin, ymax, 0.5), fontsize='x-small') plt.plot(x_list, y_list, self.tix_list[i], label='S' + str(i)) plt.legend(bbox_to_anchor=(1.15, 0.5), loc='center right', borderaxespad=0.2, fontsize='x-small') plt.savefig(self.path, format='pdf', bbox_inches='tight', pad_inches=0.3) plt.cla()
def recommend_dishes1(result): if result is not None: # plt.clf() recommend_dishes = sorted(result["recommend_dishes"].items(), key=lambda dish: dish[1], reverse=True)[:20] title = "?????" y_label = "??" labels = [dish[0] for dish in recommend_dishes] label_pos = tuple(range(len(labels))) heights = tuple([dish[1] for dish in recommend_dishes]) plt.title(title, fontsize=20) plt.ylabel(y_label) # plt.margins(0.05) plt.xticks(label_pos, labels, rotation=40) rects = plt.bar(left=label_pos, height=heights, width=0.35, align="center") bar_auto_label(rects, "?") plt.subplots_adjust(bottom=0.2) plt.show()
def topic(result): from random import randint if result: fig, ax = plt.subplots() index = tuple(range(5)) h1 = [] h2 = [] for i in range(5): h1.append(randint(20, 50)) h2.append(randint(-10, -2)) a = ax.barh(index, h1, color="r", alpha=.5) b = ax.barh(index, h2, color="b", alpha=.5) ax.set_yticks([i + 0.5 for i in index]) ax.set_yticklabels(("??", "??", "??", "??", "??")) ax.margins(0.2) ax.legend((a[0], b[0]), ('??', '??')) plt.show()
def draw_label(label, img, label_names, colormap=None): plt.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) if colormap is None: colormap = label_colormap(len(label_names)) label_viz = label2rgb(label, img, n_labels=len(label_names)) plt.imshow(label_viz) plt.axis('off') plt_handlers = [] plt_titles = [] for label_value, label_name in enumerate(label_names): fc = colormap[label_value] p = plt.Rectangle((0, 0), 1, 1, fc=fc) plt_handlers.append(p) plt_titles.append(label_name) plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5) f = io.BytesIO() plt.savefig(f, bbox_inches='tight', pad_inches=0) plt.cla() plt.close() out = np.array(PIL.Image.open(f))[:, :, :3] out = scipy.misc.imresize(out, img.shape[:2]) return out
def plot_ohlcv(self, df): fig, ax = plt.subplots() # Plot the candlestick candlestick2_ohlc(ax, df['open'], df['high'], df['low'], df['close'], width=1, colorup='g', colordown='r', alpha=0.5) # shift y-limits of the candlestick plot so that there is space # at the bottom for the volume bar chart pad = 0.25 yl = ax.get_ylim() ax.set_ylim(yl[0] - (yl[1] - yl[0]) * pad, yl[1]) # Add a seconds axis for the volume overlay ax2 = ax.twinx() ax2.set_position( matplotlib.transforms.Bbox([[0.125, 0.1], [0.9, 0.26]])) # Plot the volume overlay # bc = volume_overlay(ax2, df['open'], df['close'], df['volume'], # colorup='g', alpha=0.5, width=1) ax.xaxis.set_major_locator(ticker.MaxNLocator(6)) def mydate(x, pos): try: return df.index[int(x)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) plt.margins(0) plt.show()
def draw_scatter_graph(title, x_label, y_label, x_axis, y_axis, min_x, max_x, min_y, max_y, output_path): fig = plt.figure() fig.suptitle(title, fontsize=14, fontweight='bold') ax = fig.add_subplot(111) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.plot(x_axis, y_axis, 'o') ax.axis([min_x, max_x, min_y, max_y]) plt.margins(0.2) plt.tick_params(labelsize=10) fig.subplots_adjust(bottom=0.2) plt.savefig(output_path) plt.close(fig)
def sankey(**value): """Show SankeyWidget with default values for size and margins"""
def draw_evaluate(): xlabel = ["Rand", "Heuristi", "LR", "SVM", "MLP", "RNN", "GRU", "LSTM", "MAX"] x = range(9) plt.xticks(x, xlabel) plt.margins(0.2) y1 = [0.1, 18.8, 34.6, 36.1, 36.2, 49.4, 68.1, 63.7, 100] y2 = [-0.1, 14.3, 15.7, 15.7, 21.5, 28.0, 59.2, 53.2, 100] plt.xlim(-.2, 8.2) plt.ylim(-.5, 100) plt.plot(x, y1, 'ro-') plt.plot(x, y2, 'bo-') plt.subplots_adjust(bottom=0.15) plt.show()
def generateActivityInfoForGroup(self, groupName): timestampNow = int(time()) timestampYesterday = timestampNow - self.timestampSubtract records = list(self.coll.find({ 'to': groupName, 'timestamp': { '$gt': timestampYesterday } }).sort([ ('timestamp', DESCENDING) ])) fn = self.generateTmpFileName() # Get histogram for activity hist, bins = np.histogram([ x['timestamp'] for x in records ], bins=24) center = (bins[:-1] + bins[1:]) / 2 datex = [ datetime.fromtimestamp(x) for x in center ] pp.figure(figsize=(6,14)) ax = pp.subplot(2, 1, 1) pp.plot_date(datex, hist, '.-') pp.gcf().autofmt_xdate() pp.xlabel(u'??????', fontproperties=self.prop) pp.ylabel(u'??????', fontproperties=self.prop) ax.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M')) # Get bar chart for active users pieDat = Counter([ x['from'] for x in records ]) pieDatSorted = sorted([ (k, pieDat[k]) for k in pieDat ],key=lambda x: x[1], reverse=True) if len(pieDatSorted) > self.maxActivityInfoCount: pieDatSorted = pieDatSorted[:self.maxActivityInfoCount] ax = pp.subplot(2, 1, 2) width = 0.7 x = np.arange(len(pieDatSorted)) + width xText = [ xx[0] for xx in pieDatSorted ] y = [ xx[1] for xx in pieDatSorted ] pp.bar(x, y, width) a = pp.gca() a.set_xticklabels(a.get_xticks(), { 'fontProperties': self.prop }) pp.xticks(x, xText, rotation='vertical') pp.xlabel(u'??', fontproperties=self.prop) pp.ylabel(u'24?????', fontproperties=self.prop) ax.set_xlim([ 0, len(xText) + 1 - width ]) pp.margins(0.2) pp.savefig(fn) return fn
def confusion_matrix(confusion_data_frame, annotation_data_frame=None, fig_size=(4,4), title='Title', cmap=plt.cm.jet, pfi_where_to_save=None, show_fig=True, axis_position=None, margin=None, top_adjust=None): fig = plt.figure(figsize=fig_size) plt.clf() ax = fig.add_subplot(111) ax.set_aspect(1) res = ax.imshow(confusion_data_frame.as_matrix(), cmap=cmap, interpolation='nearest', origin='lower') rows, cols = confusion_data_frame.shape if annotation_data_frame is not None: for x in xrange(rows): for y in xrange(cols): ax.annotate(str(annotation_data_frame.as_matrix()[x, y]), xy=(y, x), horizontalalignment='center', verticalalignment='center') fig.colorbar(res) rows_index_list = list(confusion_data_frame.index) cols_index_list = list(confusion_data_frame.columns) ax.set_xticks(range(cols)) ax.set_xticklabels(cols_index_list, rotation=45, ha='center') ax.set_yticks(range(rows)) ax.set_yticklabels(rows_index_list) fig.text(.5, .05, title, ha='center') ax.invert_yaxis() ax.xaxis.tick_top() if axis_position is not None: ax.set_position(axis_position) if margin is not None: plt.margins(margin) if top_adjust is not None: plt.subplots_adjust(top=top_adjust) if pfi_where_to_save is not None: plt.savefig(pfi_where_to_save, format='pdf', dpi=200) if show_fig: plt.show()
def plotVertPro(self,i,j): if self.vplot is not None: #Create new figure that will pop-up when called fig = plt.figure(figsize=(8, 7)) fig.canvas.set_window_title('Vertical Profile at i='+str(i)+' j='+str(j)) ax = fig.add_subplot(111) ax.set_xlabel(self.VertvarTitle) ax.set_ylabel("Pressure [hPa]") ax.set_yscale('log') ax2 = ax.twinx() ax2.set_ylabel("Altitude [km]") #Read in variables ph = np.squeeze(self.dataSet.readNCVariable('PH')) phb = np.squeeze(self.dataSet.readNCVariable('PHB')) p = np.squeeze(self.dataSet.readNCVariable('P')) pb = np.squeeze(self.dataSet.readNCVariable('PB')) #Create full fields at input location press = (p[:,j,i] + pb[:,j,i])/100. height = wrf.unstaggerZ((ph + phb)/9.81)/1000. height = height[:,j,i] #Get vertical profile of input field dims = self.vplot.shape if dims[0] != len(press): dvar = wrf.unstaggerZ(self.vplot) var = dvar[:,j,i] else: var = self.vplot[:,j,i] #Create plot ax.plot(var, press, 'k', linewidth=2.0) ax.xaxis.grid(True) #ax.set_ylim(press.max()*1.02,press.min()) ax.set_ylim(1000., press.min()) #mhgt = height.min()*np.log((press.max()*1.02)/press.max()) mhgt = height.min()*np.log(1000./press.max()) ax2.set_ylim(mhgt, height.max()) subs = [0.5,2,3,4,5,6,7,8,9] loc = matplotlib.ticker.LogLocator(base=10., subs=subs) ax.yaxis.set_minor_locator(loc) ax.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter(useOffset=False)) ax.yaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter(useOffset=False)) #fmt = matplotlib.ticker.FormatStrFormatter("%g") #ax.yaxis.set_major_formatter(fmt) ax.margins(0.02) #Turn major and minor grid lines on ax.yaxis.grid(True, which='both') else: self.errorSelectVVar()
def draw_label(label, img, n_class, label_titles, bg_label=0): """Convert label to rgb with label titles. @param label_title: label title for each labels. @type label_title: dict """ from PIL import Image from scipy.misc import fromimage from skimage.color import label2rgb from skimage.transform import resize colors = labelcolormap(n_class) label_viz = label2rgb(label, img, colors=colors[1:], bg_label=bg_label) # label 0 color: (0, 0, 0, 0) -> (0, 0, 0, 255) label_viz[label == 0] = 0 # plot label titles on image using matplotlib plt.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.axis('off') # plot image plt.imshow(label_viz) # plot legend plt_handlers = [] plt_titles = [] for label_value in np.unique(label): if label_value not in label_titles: continue fc = colors[label_value] p = plt.Rectangle((0, 0), 1, 1, fc=fc) plt_handlers.append(p) plt_titles.append(label_titles[label_value]) plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=0.5) # convert plotted figure to np.ndarray f = StringIO.StringIO() plt.savefig(f, bbox_inches='tight', pad_inches=0) result_img_pil = Image.open(f) result_img = fromimage(result_img_pil, mode='RGB') result_img = resize(result_img, img.shape, preserve_range=True) result_img = result_img.astype(img.dtype) return result_img