我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.setp()。
def per_base_sequence_content_and_quality(fqbin, qualbin, outdir, figformat): fig, axs = plt.subplots(2, 2, sharex='col', sharey='row') lines = plot_nucleotide_diversity(axs[0, 0], fqbin) plot_nucleotide_diversity(axs[0, 1], fqbin, invert=True) l_Q = plot_qual(axs[1, 0], qualbin) plot_qual(axs[1, 1], qualbin, invert=True) plt.setp([a.get_xticklabels() for a in axs[0, :]], visible=False) plt.setp([a.get_yticklabels() for a in axs[:, 1]], visible=False) for ax in axs[:, 1]: ax.set_ylabel('', visible=False) for ax in axs[0, :]: ax.set_xlabel('', visible=False) # Since axes are shared I should only invert once. Twice will restore the original axis order! axs[0, 1].invert_xaxis() plt.suptitle("Per base sequence content and quality") axl = fig.add_axes([0.4, 0.4, 0.2, 0.2]) ax.plot() axl.axis('off') lines.append(l_Q) plt.legend(lines, ['A', 'T', 'G', 'C', 'Quality'], loc="center", ncol=5) plt.savefig(os.path.join(outdir, "PerBaseSequenceContentQuality." + figformat), format=figformat, dpi=500)
def make_split(ratio, gap=0.12): import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from matplotlib.ticker import MaxNLocator cax = plt.gca() box = cax.get_position() xmin, ymin = box.xmin, box.ymin xmax, ymax = box.xmax, box.ymax gs = GridSpec(2, 1, height_ratios=[ratio, 1 - ratio], left=xmin, right=xmax, bottom=ymin, top=ymax) gs.update(hspace=gap) ax = plt.subplot(gs[0]) plt.setp(ax.get_xticklabels(), visible=False) bx = plt.subplot(gs[1], sharex=ax) return ax, bx
def _plot_melodic_progression(ax3, melodic_progression, pitch, pitch_distribution): try: # plot... AudioSeyirAnalyzer.plot(melodic_progression, ax3) # axis style ax3.set_xlabel('') # remove the automatically given labels ax3.set_ylabel('') plt.setp(ax3.get_yticklabels(), visible=False) plt.setp(ax3.get_xticklabels(), visible=False) # set xlim to the last time in the pitch track ax3.set_xlim([pitch[0, 0], pitch[-1, 0]]) ax3.set_ylim([np.min(pitch_distribution.bins), np.max(pitch_distribution.bins)]) # remove the spines from the third subplot ax3.spines['bottom'].set_visible(False) ax3.spines['left'].set_visible(False) ax3.spines['right'].set_visible(False) ax3.get_yaxis().set_ticks([]) except TypeError: logging.debug('The melodic progression is not computed.')
def minimal_hbar(ss, figsize=(6,3)): tot = ss.values.sum() labels = ss.index.get_values() labelAsX = num.arange(len(labels))+1 fig, ax = plt.subplots(figsize=figsize) ax.barh(labelAsX, ss.values, align='center', color='grey') ax.set_yticks(labelAsX) ax.set_yticklabels(labels) ax.set_ylim(0, labelAsX[-1]+1) ax.set_xlim(0, max(ss.values*1.15)) ax.set_xlabel(u"Nombre d'offres") ax.grid(axis='x') plt.setp(ax.get_yticklines(), visible=False) for pos, n in zip(labelAsX, ss.values): perc = 100*float(n)/tot ax.annotate('{0:.1f}%'.format(perc), xy=(n + (max(ss.values * 0.01)), pos), color='k', fontsize=8, va='center') return fig, ax
def display(self, output_filename): fig, (ax) = plt.subplots(1, 1) data = [d.values for d in self.datasets] labels = [d.label for d in self.datasets] bp = ax.boxplot(data, labels = labels, notch = 0, sym = '+', vert = '1', whis = 1.5) plt.setp(bp['boxes'], color='black') plt.setp(bp['whiskers'], color='black') plt.setp(bp['fliers'], color='black', marker='+') for i in range(len(self.datasets)): box = bp['boxes'][i] box_x = [] box_y = [] for j in range(5): box_x.append(box.get_xdata()[j]) box_y.append(box.get_ydata()[j]) box_coords = list(zip(box_x, box_y)) box_polygon = Polygon(box_coords, facecolor = self.datasets[i].color) ax.add_patch(box_polygon) if self.title is not None: ax.set_title(self.title) x_min = np.amin([np.amin(d.values) for d in self.datasets]) x_max = np.amax([np.amax(d.values) for d in self.datasets]) ax.set_ylim(x_min - 0.05*(x_max - x_min), x_max + 0.05*(x_max - x_min)) fig.savefig(output_filename) plt.close(fig)
def __init__(self, grid_space, objects, evaluator, figsize, sleep=0.001): super(ScaleMonitor, self).__init__(evaluator, 'score_monitor') self._network = self.evaluator.network self._axes = {} self._tplot_axes = {} self._vplot_axes = {} self._fig = plt.figure(figsize=figsize) self._sleep = sleep for r_loc, name in enumerate(objects): r_span, c_span = 1, grid_space[1] self._axes[name] = plt.subplot2grid(grid_space, (r_loc, 0), colspan=c_span, rowspan=r_span) if name != objects[-1]: plt.setp(self._axes[name].get_xticklabels(), visible=False) self._axes[name].set_ylabel(r'$%s$' % name.replace(' ', r'\ ').capitalize()) self._fig.subplots_adjust(hspace=0.1) plt.ion() plt.show()
def setPlot(self,axe,seriex,seriey,seriex_selec,seriey_selec,serie_type,serie_unit): """ plot a single station """ axe.clear() axe.grid(True) if serie_type=='gravity' and seriey_selec: mean_g=np.mean(seriey_selec) axe.plot([seriex[0],seriex[len(seriex)-1]],[mean_g,mean_g],'o-',color='b',label=serie_type) axe.plot(seriex,seriey,'o-',color='k',label=serie_type) axe.plot(seriex_selec,seriey_selec,'o-',color='b',label=serie_type) axe.set_ylabel(serie_unit, size='x-small') axe.set_title(serie_type, size='x-small') labels = axe.get_xticklabels() + axe.get_yticklabels() for label in labels: label.set_size('x-small') xfmt = md.DateFormatter('%H:%M') axe.xaxis.set_major_formatter(xfmt) plt.setp(axe.get_xticklabels(), rotation=30, horizontalalignment='right') self.canvas.draw()
def _create_figure(): fig = pyplot.figure() gs = gridspec.GridSpec(3, 1, height_ratios=[2, 2, 1], hspace=0.05) ax2 = fig.add_subplot(gs[1]) ax1 = fig.add_subplot(gs[0], sharex=ax2) ax1.xaxis.set_label_position('top') ax1.xaxis.set_tick_params(labeltop='on', labelbottom='off') pyplot.setp(ax2.get_xticklabels(), visible=False) ax1.set_xscale('log') ax2.set_xscale('log') ax2.set_yscale('log') ax1.set_xlabel('Number dofs') ax1.set_ylabel('Number GMRES iterations') ax2.set_ylabel('CPU time') ax1.set_ylim(0, None, auto=True) ax2.set_ylim(0, None, auto=True) return fig, (ax1, ax2)
def _barChart(yValues, xValues, outfile): fig = plt.figure(figsize=(15,5), facecolor="black", edgecolor="white") ax = fig.add_subplot(111) ax.tick_params(axis="y", colors="black") N = len(yValues) menMeans = yValues[:N] # menStd = [2,3,4,1,2] ind = np.arange(N) width = 0.75 rects1 = ax.bar(ind, menMeans, width=width, color='black', error_kw=dict(elinewidth=2, ecolor='red')) ax.set_xlim(-width, len(ind) + width) # ax.set_ylim(0,45) ax.set_ylabel('MegaBytes') ax.set_xlabel('Date') ax.set_title('Megabytes over time') xTickMarks = xValues ax.set_xticks(ind) xtickNames = ax.set_xticklabels(xTickMarks) plt.setp(xtickNames, rotation=45, fontsize=10) #plt.show() plt.savefig(outfile) #plt.savefig()
def maybe_color_bp(self, bp): if isinstance(self.color, dict): boxes = self.color.get('boxes', self._boxes_c) whiskers = self.color.get('whiskers', self._whiskers_c) medians = self.color.get('medians', self._medians_c) caps = self.color.get('caps', self._caps_c) else: # Other types are forwarded to matplotlib # If None, use default colors boxes = self.color or self._boxes_c whiskers = self.color or self._whiskers_c medians = self.color or self._medians_c caps = self.color or self._caps_c from matplotlib.artist import setp setp(bp['boxes'], color=boxes, alpha=1) setp(bp['whiskers'], color=whiskers, alpha=1) setp(bp['medians'], color=medians, alpha=1) setp(bp['caps'], color=caps, alpha=1)
def visualizeFeatures(Features, Files, Names): y_eig, coeff = pcaDimRed(Features, 2) plt.close("all") print y_eig plt.subplot(2,1,1); ax = plt.gca() for i in range(len(Files)): im = cv2.imread(Files[i], cv2.CV_LOAD_IMAGE_COLOR) Width = 0.2; Height = 0.2; startX = y_eig[i][0]; startY = y_eig[i][1]; print startX, startY myaximage = ax.imshow(cv2.cvtColor(im, cv2.cv.CV_RGB2BGR), extent=(startX-Width/2.0, startX+Width/2.0, startY-Height/2.0, startY+Height/2.0), alpha=1.0, zorder=-1) plt.axis((-3,3,-3,3)) # Plot feaures plt.subplot(2,1,2) ax = plt.gca() for i in range(len(Files)): plt.plot(numpy.array(Features[i,:].T)); plt.xticks(range(len(Names))) plt.legend(Files) ax.set_xticklabels(Names) plt.setp(plt.xticks()[1], rotation=90) plt.tick_params(axis='both', which='major', labelsize=8) plt.tick_params(axis='both', which='minor', labelsize=8) plt.show()
def plot(ax, xl, yl, x, y, err, logx=False, xticknames=None, xlabelpad=0): if xl is not None: ax.set_xlabel(xl, labelpad=xlabelpad) if yl is not None: ax.set_ylabel(yl) ax.errorbar(x, y, fmt='o-', yerr=err) ax.set_xlim(x[0]-0.1, x[-1]+0.1) ax.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5) ax.grid(True, linestyle='-', which='minor', color='lightgrey', alpha=0.5, axis='x') if logx: ax.set_xscale('log') if xticknames is not None: # xn = ax.set_xticklabels(xticknames) ax.xaxis.set_major_locator(IndexLocator(1, 0)) # xn = plt.setp(ax, xticklabels=xticknames) # plt.setp(xn, rotation=90, fontsize=8) if len(err.shape) > 1: ax.set_ylim((y-err[0]).min()-(0.1*y.min()), (y+err[1]).max()+(0.1*y.max())) else: ax.set_ylim((y-err).min()-(0.1*y.min()), (y+err).max()+(0.1*y.max()))
def scatter_crimes_population(): """creates a scatter plot using the values of Population and Crimes Per 100000. iterates through the database and reads all the data in the given headers and creates plots for each data point """ x = df["Number of Crimes"].values y = df["Population"].values assert len(x) == len(y) df["Crimes Per 100000"] = np.array([(x[i] / y[i]) * 100000.0 for i in range(len(x))], dtype="float32") ax = df.plot.scatter(y="Population", x="Crimes Per 100000") for index, row in df.iterrows(): ax.annotate(row["Community Name"], (row["Crimes Per 100000"], row["Population"]), size=7, color='darkslategrey') x = df["Crimes Per 100000"].values y = df["Population"].values m, b = np.polyfit(x, y, 1) line = plt.plot(x, m * x + b, 'b--') plt.setp(line, color='orange', alpha=0.5, linewidth=2.0) plt.show()
def inset_title_box(ax,title,bwidth="20%",location=1): """ Function that puts title of subplot in a box :ax: Name of matplotlib axis to add inset title text box too :title: 'string to put inside text box' :returns: @todo """ axins = inset_axes(ax, width=bwidth, # width = 30% of parent_bbox height=.30, # height : 1 inch loc=location) plt.setp(axins.get_xticklabels(), visible=False) plt.setp(axins.get_yticklabels(), visible=False) axins.set_xticks([]) axins.set_yticks([]) axins.text(0.5,0.3,title, horizontalalignment='center', transform=axins.transAxes,size=10)
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ plt.setp(self.x_ax.get_xticklabels(), visible=False) plt.setp(self.y_ax.get_yticklabels(), visible=False) plt.setp(self.x_ax.yaxis.get_majorticklines(), visible=False) plt.setp(self.x_ax.yaxis.get_minorticklines(), visible=False) plt.setp(self.y_ax.xaxis.get_majorticklines(), visible=False) plt.setp(self.y_ax.xaxis.get_minorticklines(), visible=False) plt.setp(self.x_ax.get_yticklabels(), visible=False) plt.setp(self.y_ax.get_xticklabels(), visible=False) self.x_ax.yaxis.grid(False) self.y_ax.xaxis.grid(False) self.fig.suptitle("Joint Plot of {} vs {}" .format(self.feature, self.target), y=1.05)
def plot_time_corrs(subjects, axes): x = np.arange(1, 5) palette = [".2", ".5"] for subj, ax in zip(subjects, axes): res_fname = "correlation_analysis/{}_rest_ifs.pkz".format(subj) res = moss.load_pkl(res_fname) for line, color in zip(res.corr_times.T, palette): ax.plot(x, line, "o-", color=color, ms=3, clip_on=False) sig = res.corr_times_pctiles > 95 ax.plot(x[sig], np.ones(sig.sum()) * .0025, marker=(6, 2, 0), ls="", mew=.35, mec=".2", ms=3) ax.set(xticks=x, xlim=(.6, 4.4), ylim=(0, .07)) sns.despine(ax=ax, trim=True) plt.setp(axes[1:], yticklabels=[]) axes[0].set_ylabel("Correlation (r)")
def plot_colorbars(f, axes): dots, sticks = get_colormap("dots"), get_colormap("sticks") xx = np.arange(200).reshape(1, 200) axes[0].imshow(xx, rasterized=True, aspect="auto", cmap=dots) axes[1].imshow(xx, rasterized=True, aspect="auto", cmap=sticks) kws = dict(size=7, ha="center") f.text(.08, .015, "Motion", **kws) f.text(.24, .015, "Color", **kws) f.text(.32, .015, "Orientation", **kws) f.text(.48, .015, "Color", **kws) plt.setp(axes, xticks=[], yticks=[])
def plot_data(X_train, y_train, plot_row=5): counts = dict(Counter(y_train)) num_classes = len(np.unique(y_train)) f, axarr = plt.subplots(plot_row, num_classes) for c in np.unique(y_train): # Loops over classes, plot as columns c = int(c) ind = np.where(y_train == c) ind_plot = np.random.choice(ind[0], size=plot_row) for n in range(plot_row): # Loops over rows axarr[n, c].plot(X_train[ind_plot[n], :]) # Only shops axes for bottom row and left column if n == 0: axarr[n, c].set_title('Class %.0f (%.0f)' % (c, counts[float(c)])) if not n == plot_row - 1: plt.setp([axarr[n, c].get_xticklabels()], visible=False) if not c == 0: plt.setp([axarr[n, c].get_yticklabels()], visible=False) f.subplots_adjust(hspace=0) # No horizontal space between subplots f.subplots_adjust(wspace=0) # No vertical space between subplots plt.show() return
def plot_lwc(ax, data): """ Plots liquid water content timeseries i.e. cloud status """ plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) #ax.grid(False) #ax.text(0.5, 0.5, 'TODO: Will show cloud status IN/OUT', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) if 'LWC_JW_U' in data.keys(): lwc=data['LWC_JW_U'][:,0] elif 'NV_LWC_C' in data.keys(): lwc=data['NV_LWC_C'][:,0] elif 'NV_LWC_U' in data.keys(): lwc=data['NV_LWC_U'][:,0] else: return lwc = np.clip(lwc, 0, 1) ax.plot_date(data['mpl_timestamp'][:,0], lwc, '-') ax.set_ylabel('lwc') ax.set_ylim(0, 1.1) return ax
def plot_alt_ts(ax, data): """ Plots the lamp temperature """ ax.set_ylabel('GPS alt (km)') ax.plot_date(data['mpl_timestamp'][:, 0].ravel(), data['ALT_GIN'][:, 0].ravel()/1000., '-', lw=2) ax.text(0.05, 0.98, 'Altitude', axes_title_style, transform=ax.transAxes) plt.setp(ax.get_xticklabels(), visible=False) return ax
def plot_lwc(ax, data): """ plots liquid water content timeseries i.e. cloud status """ if not 'LWC_JW_U' in data: return plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) #ax.text(0.5, 0.5, 'TODO: Will show cloud status IN/OUT', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) lwc=data['LWC_JW_U'][:,0] lwc=np.clip(lwc, 0, 1) ax.plot_date(data['mpl_timestamp'][:,0], lwc, '-') ax.set_ylabel('lwc') ax.set_ylim(0, 1.1) return ax
def plot_heater(ax, data): """ plots deiced heater status i.e. ON/OFF """ if not 'PRTAFT_deiced_temp_flag' in data: return ax.text(0.05, 0.98,'Heater', axes_title_style, transform=ax.transAxes) ax.grid(False) ax.set_ylim(0,1) ax.yaxis.set_major_locator(plt.NullLocator()) plt.setp(ax.get_xticklabels(), visible=False) heater_status=np.array(data['PRTAFT_deiced_temp_flag'], dtype=np.int8) toggle=np.diff(heater_status.ravel()) time_periods=zip(list(np.where(toggle == 1)[0]), list(np.where(toggle == -1)[0])) for t in time_periods: #plt.barh(0, data['mpl_timestamp'][0,1], left=data['mpl_timestamp'][0,0]) width=data['mpl_timestamp'][t[1],0]-data['mpl_timestamp'][t[0],0] ax.add_patch(patches.Rectangle((data['mpl_timestamp'][t[0],0], 0), width, 1, alpha=0.8, color='#ffaf4d')) return ax
def plot_sun_position(ax, data): """ Creates time series plot for the sun position. 0: sun on the nose 90: sun starboard 180: sun on the tail 270: sun on port side :param ax: axes object :param data: data dictionary """ # sun position in reference to the aircraft heading # 0: sun on the nose # 90: sun starboard # 180: sun from behind # 270: sun on port side ax.plot_date(data['mpl_timestamp'][:, 0].ravel(), data['sun_position'], '-', lw=2, label='Sun position') ax.set_ylim(0, 360) ax.yaxis.set_ticks(np.arange(0.0, 361.0, 90.0)) ax.legend(loc='upper right') plt.setp(ax.get_xticklabels(), visible=False) return ax
def plot_pyrgeometers_ts(ax,data): """ Creates timeseries plot for the pyrgeometers """ # these are yet to be fitted; will update to include when ready. plt.setp(ax.get_xticklabels(), visible=False) ax.text(0.05, 0.98, 'Pyrgeometers - corrected longwave irradiance', axes_title_style, transform=ax.transAxes) ax.set_ylabel('Irradiance (W m -2)') yl = ax.get_ylim() if yl[1] > 1500: ax.set_ylim(yl[0], 1500) ax.legend() return ax
def plot_matrix2(self, labels=None, **kwargs): """ Plot distance matrix and dendrogram using seaborn. This package needs to be installed manually. Parameters ---------- kwargs dict Keyword arguments to be passed to seaborn.clustermap. See http://seaborn.pydata.org/generated/seaborn.clustermap.html Returns ------- seaborn.clustermap """ try: import seaborn as sns except: raise ImportError('Need seaborn package installed.') cg = sns.clustermap( self.mat, row_linkage=self.linkage, col_linkage=self.linkage, **kwargs) # Rotate labels plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), rotation=90) plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0) # Make labels smaller plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), fontsize=4) plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), fontsize=4) # Increase padding cg.fig.subplots_adjust(right=.8, top=.95, bottom=.2) module_logger.info( 'Use matplotlib.pyplot.show() to render figure.') return cg
def plotCandlestick(symbol, dates, title="Selected data"): quotes = loadStockQuotes(symbol, dates) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() ax.set_title(title) plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
def plotCandlestick(symbol, startdate, enddate, title="Selected data"): quotes = loadStockQuotes(symbol, startdate, enddate) print(quotes) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 # dayFormatter = DateFormatter('%d') # e.g., 12 fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() ax.set_title(title) plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
def plotCandlestick(symbol, start_index, end_index, title="Selected data"): dates = pd.date_range(start_index, end_index) quotes = utl.loadStockQuotes(symbol, dates) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
def subplots_demo6(): x = np.linspace(0, 2 * np.pi, 300) y = np.sin(x ** 2) f, ax_arr = plt.subplots(2, 2) ax_arr[0, 0].plot(x, y) ax_arr[0, 0].set_title('axis 0, 0') ax_arr[0, 1].scatter(x, y) ax_arr[0, 1].set_title('axis 0, 1') ax_arr[1, 0].plot(x, y ** 2) ax_arr[1, 0].set_title('axis 1, 0') ax_arr[1, 1].scatter(x, y ** 2) ax_arr[1, 1].set_title('axis 1, 1') # for row 0, every element x axis hidden plt.setp([ax.get_xticklabels() for ax in ax_arr[0, :]], visible=False) # for column 1, every element y axis hidden plt.setp([ax.get_yticklabels() for ax in ax_arr[:, 1]], visible=False) plt.show()
def makedistplots(ppdf1,pamt1,bincrates): #### This is how we'll normalize to get changes per degree warming. dry=ppdf1[0]*100 # Change in dry days # % rain rates in mm/d for x axis ticks and labeling otn=np.linspace(1,9,9) xtickrates=np.append(0,otn*.1) xtickrates=np.append(xtickrates,otn) xtickrates=np.append(xtickrates,otn*10) xtickrates=np.append(xtickrates,otn*100) xticks=np.interp(xtickrates,bincrates,range(0,len(bincrates))); #% bin numbers associated with nice number rain rate xticks,indices=np.unique(xticks,return_index=True) xtickrates=xtickrates[indices] ### Bin width - needed to normalize the rain amount distribution db=(bincrates[2]-bincrates[1])/bincrates[1]; ### Now we plot plt.figure(figsize=(4,6)) plt.clf() ax=plt.subplot(211) plt.plot(range(0,len(pamt1)),pamt1/db, 'k') #plt.ylim((-.05,.15)) plt.xlim((4,130)) #plt.setp(ax,xticks=xticks,xticklabels=['0','0.1','','','','','','','','','','1','','','','','','','','','10','','','','','','','','','100','','','','','','','','','1000']) plt.setp(ax,xticks=xticks,xticklabels=['']) #plt.xlabel('Rain rate (mm/d)') plt.title('Rain amount (mm/d)') ax=plt.subplot(212) plt.plot(range(0,len(ppdf1)),ppdf1*100, 'k') plt.plot((0,len(ppdf1)),(0,0),'0.5') plt.xlim((4,130)) ### Annotate with the dry day frequency ymin, ymax = ax.get_ylim() t=plt.text(4,ymax*0.95, "{:.1f}".format(dry)+'%') plt.setp(t,va='top',ha='left') plt.setp(ax,xticks=xticks,xticklabels=['0','0.1','','','','','','','','','','1','','','','','','','','','10','','','','','','','','','100','','','','','','','','','1000']) plt.xlabel('Rain rate (mm/d)') plt.title('Rain frequency (%)') plt.savefig("rainmetricdemo.pdf") return ### Call the function to make the rain distribution
def plot_density(self, ax, num=300, **kwargs): """Returns a density plot on an Pyplot Axes object. Args: ax (:obj:`Axes`): An matplotlib Axes object on which the histogram will be plot num (:obj:`int`): The number of x values the line is plotted on. Default: 300 **kwargs: Keyword arguments that are passed on to the pyplot.plot function. """ colors = [] self.build() bin_centers = np.asarray(self._get_bin_centers()) x_new = np.linspace(bin_centers.min(), bin_centers.max(), num) if 'color' in kwargs: colors = kwargs['color'] del kwargs['color'] power_smooth = [] for (colname, bin_values) in self.hist_dict.items(): normed_values, ble = np.histogram(self._get_bin_centers(), bins=self.bin_list, weights=bin_values, normed=True ) power_smooth.append(x_new) power_smooth.append(spline(bin_centers, normed_values, x_new)) lines = ax.plot(*power_smooth, **kwargs) for i, line in enumerate(lines): if len(colors) > 0: plt.setp(line, color=colors[i], label=list(self.hist_dict.keys())[i]) else: plt.setp(line, label=list(self.hist_dict.keys())[i]) return lines
def make_pie(size, values, labels, title): """ make a pie chart using matplotlib. return the chart as a pygame surface make the pie chart a square that is as tall as the display. """ logging.debug('make_pie(...,...,%s)', title) inches = size[1] / 100.0 fig = plt.figure(figsize=(inches, inches), dpi=100, tight_layout={'pad': 0.10}, facecolor='k') ax = fig.add_subplot(111) ax.pie(values, labels=labels, autopct='%1.1f%%', textprops={'color': 'w'}, wedgeprops={'linewidth': 0.25}, colors=('b', 'g', 'r', 'c', 'm', 'y', '#ff9900', '#00ff00', '#663300')) ax.set_title(title, color='white', size=48, weight='bold') handles, labels = ax.get_legend_handles_labels() legend = ax.legend(handles[0:5], labels[0:5], title='Top %s' % title, loc='lower left') # best frame = legend.get_frame() frame.set_color((0, 0, 0, 0.75)) frame.set_edgecolor('w') legend.get_title().set_color('w') for text in legend.get_texts(): plt.setp(text, color='w') canvas = agg.FigureCanvasAgg(fig) canvas.draw() renderer = canvas.get_renderer() raw_data = renderer.tostring_rgb() plt.close(fig) canvas_size = canvas.get_width_height() logging.debug('make_pie(...,...,%s) done', title) return raw_data, canvas_size
def plot_errorbar_bbox_stats(self, stats_w, stats_h, base_names, path): """Plot the errorbar graph of the bbox mean+-std (of the width or hieght) of multiple sets. stats_w/h= listof tuplet (mean, std) of the w (h) """ fig, axs = plt.subplots(nrows=1, ncols=2, sharex=True) ax_w = axs[0] ax_h = axs[1] i=1 for data_w, data_h in zip(stats_w, stats_h): ax_w.errorbar(x=i, y=data_w[0], yerr=data_w[1], fmt='o', label=base_names[i-1] ) ax_h.errorbar(x=i, y=data_h[0], yerr=data_h[1], fmt='o', label=base_names[i-1] ) i +=1 # hide the xlabels plt.setp(ax_w.get_xticklabels(), visible=False) plt.setp(ax_h.get_xticklabels(), visible=False) # st the x axis limits. ax = plt.gca() ax.set_xlim([-0.5, len(base_names)+1]) ax_w.set_title('mean(hight) +- std(hieght) of bbox', fontsize=10) ax_h.set_title('mean(hight) +- std(hieght) of bbox', fontsize=10) ax_w.legend(numpoints=1, fancybox=True, shadow=True, prop={'size':6}) ax_h.legend(numpoints=1, fancybox=True, shadow=True, prop={'size':6}) fig.suptitle('Statistics over the bounding box width and hieght of mutliple datasets.') fig.savefig(path, bbox_inches='tight')
def create_summary_graph(title, y_axis_label, labels, values): """Create summary (column) graph for any measurement.""" N = len(values) indexes = np.arange(N) fig = plt.figure() plt.xlabel("call #") plt.ylabel(y_axis_label) plt.grid(True) plt.xticks(indexes, labels) locs, plt_labels = plt.xticks() plt.setp(plt_labels, rotation=90) plt.bar(indexes, values, 0.80, color='yellow', edgecolor='black', label=title) # plt.legend(loc='lower right') for tick in plt_labels: tick.set_horizontalalignment("left") tick.set_verticalalignment("top") tick.set_visible(False) for tick in plt_labels[::5]: tick.set_visible(True) plt.tick_params(axis='x', which='major', labelsize=10) fig.subplots_adjust(bottom=0.4) fig.suptitle(title) return fig
def create_statistic_graph(title, y_axis_label, labels, min_values, max_values, avg_values, x_axis_label="pause time (seconds)", width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, dpi=DPI): """Create summary (column) graph with min, average, and max values.""" N = len(labels) indexes = np.arange(N) fig = plt.figure(figsize=(1.0 * width / dpi, 1.0 * height / dpi), dpi=dpi) plt.xlabel(x_axis_label) plt.ylabel(y_axis_label) plt.grid(True) plt.xticks(indexes, labels) locs, plt_labels = plt.xticks() plt.setp(plt_labels, rotation=90) plt.bar(indexes - 0.27, min_values, 0.25, color='red', edgecolor='black', label='min values') plt.bar(indexes, avg_values, 0.25, color='yellow', edgecolor='black', label='avg values') plt.bar(indexes + 0.27, max_values, 0.25, color='green', edgecolor='black', label='max values') plt.legend(loc='upper left') for tick in plt_labels: tick.set_horizontalalignment("left") tick.set_verticalalignment("top") plt.tick_params(axis='x', which='major', labelsize=10) # fig.subplots_adjust(bottom=0.4) fig.suptitle(title) return fig
def plot_attention(src_words, trg_words, attention_matrix, file_name=None): """This takes in source and target words and an attention matrix (in numpy format) and prints a visualization of this to a file. :param src_words: a list of words in the source :param trg_words: a list of target words :param attention_matrix: a two-dimensional numpy array of values between zero and one, where rows correspond to source words, and columns correspond to target words :param file_name: the name of the file to which we write the attention """ fig, ax = plt.subplots() #a lazy, rough, approximate way of making the image large enough fig.set_figwidth(int(len(trg_words)*.6)) # put the major ticks at the middle of each cell ax.set_xticks(np.arange(attention_matrix.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(attention_matrix.shape[0]) + 0.5, minor=False) ax.invert_yaxis() # label axes by words ax.set_xticklabels(trg_words, minor=False) ax.set_yticklabels(src_words, minor=False) ax.xaxis.tick_top() plt.setp(ax.get_xticklabels(), rotation=50, horizontalalignment='right') # draw the heatmap plt.pcolor(attention_matrix, cmap=plt.cm.Blues, vmin=0, vmax=1) plt.colorbar() if file_name != None: plt.savefig(file_name, dpi=100) else: plt.show() plt.close()
def _plot_pitch_dist_note_models(cls, ax2, note_models, pitch_distribution): # plot pitch distribution try: ax2.plot(pitch_distribution.vals, pitch_distribution.bins, color='gray') except AttributeError: logging.debug('The pitch distribution is not computed.') return # plot note models if note_models is not None: ytick_vals = cls._plot_note_models( ax2, note_models, pitch_distribution) else: peak_idx = pitch_distribution.detect_peaks()[0] ytick_vals = pitch_distribution.bins[peak_idx] # set the frequency ticks and grids ax2.set_yticks(ytick_vals) plt.setp(ax2.get_yticklabels(), visible=False) # define xlim higher than the highest peak so the note names have space ax2.set_xlim([0, 1.2 * max(pitch_distribution.vals)]) # remove spines from the second subplot ax2.spines['top'].set_visible(False) ax2.spines['bottom'].set_visible(False) ax2.spines['left'].set_visible(False) ax2.spines['right'].set_visible(False) # remove the axis of the subplot 2 ax2.axis('off')
def extinction_figure(wave, a_lambda, residual_from, residual_lims=(-0.1, 0.4), title_text='$R_V = 3.1$'): names = list(a_lambda.keys()) # consistent ordering between panels fig = plt.figure(figsize=(8.5, 6.)) ax = plt.axes() for name in names: plt.plot(wave, a_lambda[name], label=name) plt.axvline(x=2700., ls=':', c='k') plt.axvline(x=3030.3030, ls=':', c='k') plt.axvline(x=9090.9091, ls=':', c='k') plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000) plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000) plt.text(0.65, 0.95, title_text, transform=ax.transAxes, va='top', ha='right', size='x-large') plt.ylabel('Extinction ($A(\lambda)$ / $A_V$)') plt.legend() plt.setp(ax.get_xticklabels(), visible=False) divider = make_axes_locatable(ax) axresid = divider.append_axes("bottom", size=2.0, pad=0.2, sharex=ax) for name in names: plt.plot(wave, a_lambda[name] - a_lambda[residual_from]) plt.axvline(x=2700., ls=':', c='k') plt.axvline(x=3030.3030, ls=':', c='k') plt.axvline(x=9090.9091, ls=':', c='k') plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000) plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000) plt.xlim(wave[0], wave[-1]) plt.ylim(ymin=residual_lims[0], ymax=residual_lims[1]) plt.ylabel('residual from ' + residual_from) plt.xlabel(r'Wavelength ($\mathrm{\AA}$)') ax.set_xscale('log') axresid.set_xscale('log') plt.tight_layout() return fig
def wrcontour(dir, var, **kwargs): fig = plt.figure() rect = [0.1, 0.1, 0.8, 0.8] ax = WindroseAxes(fig, rect) fig.add_axes(ax) ax.contour(dir, var, **kwargs) l = ax.legend(axespad=-0.10) plt.setp(l.get_texts(), fontsize=8) plt.draw() plt.show() return ax
def wrcontourf(dir, var, **kwargs): fig = plt.figure() rect = [0.1, 0.1, 0.8, 0.8] ax = WindroseAxes(fig, rect) fig.add_axes(ax) ax.contourf(dir, var, **kwargs) l = ax.legend(axespad=-0.10) plt.setp(l.get_texts(), fontsize=8) plt.draw() plt.show() return ax
def wrbox(dir, var, **kwargs): fig = plt.figure() rect = [0.1, 0.1, 0.8, 0.8] ax = WindroseAxes(fig, rect) fig.add_axes(ax) ax.box(dir, var, **kwargs) l = ax.legend(axespad=-0.10) plt.setp(l.get_texts(), fontsize=8) plt.draw() plt.show() return ax
def wrbar(dir, var, **kwargs): fig = plt.figure() rect = [0.1, 0.1, 0.8, 0.8] ax = WindroseAxes(fig, rect) fig.add_axes(ax) ax.bar(dir, var, **kwargs) l = ax.legend(axespad=-0.10) plt.setp(l.get_texts(), fontsize=8) plt.draw() plt.show() return ax
def set_legend(ax): """Create a legend for the wind rose.""" l = ax.legend(borderaxespad=-0.10) plt.setp(l.get_texts(), fontsize=8)
def rotate_annotations(self, grid): for ax in grid.fig.axes: #ax.get_xaxis().get_major_formatter().set_scientific(False) xtl = ax.get_xticklabels() ytl = ax.get_yticklabels() plt.setp(xtl, rotation="horizontal") plt.setp(ytl, rotation="horizontal") sns_overlap = sns.utils.axis_ticklabels_overlap(xtl) if sns_overlap: grid.fig.autofmt_xdate()
def despine(ax): for spine in ax.spines: ax.spines[spine].set_visible(False) plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False)
def plot_objective(): x, y = np.meshgrid(np.arange(-6, 6, 0.1), np.arange(-6, 6, 0.1)) z = np.array([[objective.feedback([y[i, j], x[i, j]]) for i in range(x.shape[0])] for j in range(x.shape[1])]) plt.contourf(x, y, z, cmap=plt.cm.Blues, levels=np.linspace(z.min(), z.max(), 30)) plt.setp(plt.gca(), xticks=(), yticks=(), xlim=(-5, 5), ylim=(-5, 5))
def prepare(ax, bl, **kwargs): bl = bl.line ticks_locations = beamline_get_ticks_locations(bl) ticks_labels = beamline_get_ticks_labels(bl) ax.tick_params(axis='both', which='major') ax.tick_params(axis='x', labelsize=6) ax.xaxis.set_major_locator(FixedLocator(ticks_locations)) ax.set_xlim([ticks_locations[0], ticks_locations[-1]]) ax.get_xaxis().set_tick_params(direction='out') plt.setp(ax.xaxis.get_majorticklabels(), rotation=-45) ax.yaxis.set_major_locator(MultipleLocator(10)) ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.set_ylim(kwargs.get('ylim', [-60, 60])) ax.set_xlim([ticks_locations[0], ticks_locations[-1]]) ax.set_xlabel('s (m)') ax.set_ylabel(r'Beam size (mm)') ax.grid(False, alpha=0.25) if kwargs.get('print_label', True): ax2 = ax.twiny() ax2.set_xlim([ticks_locations[0], ticks_locations[-1]]) ax2.get_xaxis().set_tick_params(direction='out') ax2.tick_params(axis='both', which='major') ax2.tick_params(axis='x', labelsize=6) plt.setp(ax2.xaxis.get_majorticklabels(), rotation=-90) ax2.xaxis.set_major_formatter(FixedFormatter(ticks_labels)) ax2.xaxis.set_major_locator(FixedLocator(ticks_locations)) if kwargs.get("size_arrows", False): ax.set_yticklabels([str(abs(x)) for x in ax.get_yticks()]) ax.annotate('', xy=(-0.103, 0.97), xytext=(-0.103, 0.75), arrowprops=dict(arrowstyle="->", color='k'), xycoords=ax.transAxes) ax.annotate('', xy=(-0.103, 0.25), xycoords='axes fraction', xytext=(-0.103, 0.03), arrowprops=dict(arrowstyle="<-", color='k')) ax.text(-0.126, 0.86, "Vertical", fontsize=7, rotation=90, transform=ax.transAxes) ax.text(-0.126, 0.22, "Horizontal", fontsize=7, rotation=90, transform=ax.transAxes)
def plot_analyzed_dataframe(pair: str) -> None: """ Calls analyze() and plots the returned dataframe :param pair: pair as str :return: None """ # Init Bittrex to use public API exchange._API = exchange.Bittrex({'key': '', 'secret': ''}) dataframe = analyze.analyze_ticker(pair) # Two subplots sharing x axis fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True) fig.suptitle(pair, fontsize=14, fontweight='bold') ax1.plot(dataframe.index.values, dataframe['close'], label='close') # ax1.plot(dataframe.index.values, dataframe['sell'], 'ro', label='sell') ax1.plot(dataframe.index.values, dataframe['sma'], '--', label='SMA') ax1.plot(dataframe.index.values, dataframe['tema'], ':', label='TEMA') ax1.plot(dataframe.index.values, dataframe['blower'], '-.', label='BB low') ax1.plot(dataframe.index.values, dataframe['buy_price'], 'bo', label='buy') ax1.legend() ax2.plot(dataframe.index.values, dataframe['adx'], label='ADX') ax2.plot(dataframe.index.values, dataframe['mfi'], label='MFI') # ax2.plot(dataframe.index.values, [25] * len(dataframe.index.values)) ax2.legend() ax3.plot(dataframe.index.values, dataframe['fastk'], label='k') ax3.plot(dataframe.index.values, dataframe['fastd'], label='d') ax3.plot(dataframe.index.values, [20] * len(dataframe.index.values)) ax3.legend() # Fine-tune figure; make subplots close to each other and hide x ticks for # all but bottom plot. fig.subplots_adjust(hspace=0) plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False) plt.show()
def plot_data(self, series): f, (ax1) = plt.subplots(1, 1, sharex=True, sharey=False, figsize=(5.0, 4.0)) data_xtick_labels = self.data["10"].keys() data_xticks = [int(x) for x in data_xtick_labels] ylabel = None if series == "mean": ylabel = "Mean Latency" elif series == "sd": ylabel = "Standard Deviation of Latency" elif series == "sem": ylabel = "Standard Error of Mean of Latency" self.plot_lines_with_error_bars(series, ax1, "Per Link Latency", ylabel, "", y_scale='linear', x_min_factor=0.75, x_max_factor=1.1, y_min_factor=0.9, y_max_factor=1, xticks=data_xticks, xtick_labels=data_xtick_labels) xlabels = ax1.get_xticklabels() plt.setp(xlabels, rotation=0, fontsize=10) # Shrink current axis's height by 25% on the bottom box = ax1.get_position() ax1.set_position([box.x0, box.y0 + box.height * 0.3, box.width, box.height * 0.7]) handles, labels = ax1.get_legend_handles_labels() ax1.legend(handles, labels, shadow=True, fontsize=10, loc='upper center', ncol=2, markerscale=1.0, frameon=True, fancybox=True, columnspacing=0.5, bbox_to_anchor=[0.5, -0.25]) plt.savefig(series + "_latency_evaluation_" + self.evaluation_type + ".png", dpi=1000) plt.show()