我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用matplotlib.pyplot.axvspan()。
def plot_events_with_event_scores(gt_event_scores, detected_event_scores, ground_truth_events, detected_events, show=True): fig = plt.figure(figsize=(10, 3)) for i in range(len(detected_events)): d = detected_events[i] plt.axvspan(d[0], d[1], 0, 0.5) plt.text((d[1] + d[0]) / 2, 0.2, detected_event_scores[i], horizontalalignment='center', verticalalignment='center') for i in range(len(ground_truth_events)): gt = ground_truth_events[i] plt.axvspan(gt[0], gt[1], 0.5, 1) plt.text((gt[1] + gt[0]) / 2, 0.8, gt_event_scores[i], horizontalalignment='center', verticalalignment='center') plt.tight_layout() if show: plt.show() else: plt.draw()
def cb(y, P, counter, current): solution = np.empty(len(y)) for v, w, f, l in P: solution[f:f + l] = max(v, 0) / w * g**np.arange(l) plt.figure(figsize=(3, 3)) color = y.copy() plt.plot(solution, c='k', zorder=-11, lw=1.2) plt.scatter(np.arange(len(y)), solution, s=60, cmap=plt.cm.Spectral, c=color, clip_on=False, zorder=11) plt.scatter([np.arange(len(y))[current]], [solution[current]], s=200, lw=2.5, marker='+', color='b', clip_on=False, zorder=11) for a in P[::2]: plt.axvspan(a[2], a[2] + a[3], alpha=0.1, color='k', zorder=-11) for x in np.where(trueSpikes)[0]: plt.plot([x, x], [0, 1.65], lw=1.5, c='r', zorder=-12) plt.xlim((0, len(y) - .5)) plt.ylim((0, 1.65)) simpleaxis(plt.gca()) plt.xticks([]) plt.yticks([]) if save_figs: plt.savefig('fig/%d.pdf' % counter) plt.show() # generate data
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 memory_timeline(output, data_list): """Plots all the data in data_list into a single axis, pinning the y-axis minimum at zero. This plot was created to compare multiple executions of the application, removing skew in both axes. """ import matplotlib.pyplot as plt data_list = sorted(data_list, key=lambda list_: list_[0][TIMESTAMP]) fig, memory_axes = plt.subplots() last_ts = None memory_max = 0 for data in data_list: timestamp = [line[TIMESTAMP] for line in data] memory = [line[MEMORY] for line in data] memory_max = max(max(memory), memory_max) memory_axes.plot(timestamp, memory, color='b') if last_ts is not None: plt.axvspan(last_ts, timestamp[0], color='y', alpha=0.1, lw=0) last_ts = timestamp[-1] memory_max *= 1.1 memory_axes.set_ylim(0, memory_max) plot_date_axis(memory_axes) memory_axes.set_ylabel('Memory (MB)', color='b') plot_configure(fig) plt.savefig(output)
def latency_scatter(output, data_list, interval): import matplotlib.pyplot as plt fig, axes = plt.subplots() data_list = sorted(data_list, key=lambda list_: list_[0]) timestamp, latency = [], [] for timestamps in data_list: last = timestamps.pop(0) for current in timestamps: timedelta = current - last # seconds = timedelta.total_seconds() - interval seconds = timedelta.total_seconds() timestamp.append(current) latency.append(seconds) last = current if latency: axes.set_ylabel('Latency (sec)') axes.scatter(timestamp, latency, s=10, alpha=0.1, marker=',', edgecolors='none') axes.set_xlim(min(timestamp), max(timestamp)) axes.set_ylim(0, max(latency) * 1.1) last_ts = None for timestamps in data_list: if not timestamps: continue if last_ts is not None: plt.axvspan(last_ts, timestamps[0], color='y', alpha=0.1, lw=0) last_ts = timestamps[-1] plot_date_axis(axes) plot_configure(fig) plt.savefig(output)
def colortsplot(df, filename, dpi): init_plotting(8.5,3) colors = {'Release_Demand': 'cornsilk', 'Hedge_90': 'indianred', 'Hedge_80': 'indianred', 'Hedge_70': 'indianred', 'Hedge_60': 'indianred', 'Hedge_50': 'indianred', 'Flood_Control': 'lightsteelblue'} df.storage.plot(color='0.6', linewidth=2) df.Ss.plot(color='k', linewidth=2, zorder=10) for pol in set(df.policy): first = df.index[(df.policy == pol) & (df.policy.shift(1) != pol)] last = df.index[(df.policy == pol) & (df.policy.shift(-1) != pol)] for f,l in zip(first,last): plt.axvspan(f,l+pd.Timedelta('1 day'), facecolor=colors[pol], edgecolor='none', alpha=0.4) plt.legend(['Observed', 'Policy Tree'], loc=3, ncol=2) plt.ylim([0,1000]) plt.ylabel('Storage (TAF)') plt.tight_layout() plt.savefig(filename, dpi=dpi) plt.close()
def get_timestamps(args, url, name): """ ?????????????? """ plt.figure() data = request.urlopen("http://b.hatena.ne.jp/entry/json/{}".format(url)).read().decode("utf-8") info = json.loads(data.strip('(').rstrip(')'), "r") timestamps = list() if info != None and "bookmarks" in info.keys(): # ????????????????????????? bookmarks=info["bookmarks"] title = info["title"] for bookmark in bookmarks: timestamp = datetime.datetime.strptime(bookmark["timestamp"],'%Y/%m/%d %H:%M:%S') timestamps.append(timestamp) timestamps = list(reversed(timestamps)) # ?????????????????? count = len(timestamps) number = range(count) if(count!=0): first = timestamps[0] plt.plot(timestamps,number,"-o",lw=3,color="#444444") # 3???3 plt.axvspan(first,first+datetime.timedelta(hours=3),alpha=0.1,color="blue") plt.plot([first,first+datetime.timedelta(days=2)],[3,3],"--",alpha=0.9,color="blue",label="new entry") # 12???15 plt.axvspan(first+datetime.timedelta(hours=3),first+datetime.timedelta(hours=12),alpha=0.1,color="green") plt.plot([first,first+datetime.timedelta(days=2)],[15,15],"--",alpha=0.9, color="green",label="popular entry") # ?????? plt.plot([first,first+datetime.timedelta(days=2)],[15,15],"--",alpha=0.7, color="red",label="hotentry") plt.xlim(first,first+datetime.timedelta(days=2)) plt.title(name) plt.xlabel("First Hatebu : {}".format(first)) plt.legend(loc=4) plt.savefig(args.directory+"/hatebu/{}.png".format(name)) plt.close()
def _periodogram_plot(title, column, data, trend, peaks): """display periodogram results using matplotlib""" periods, power = periodogram(data) plt.figure(1) plt.subplot(311) plt.title(title) plt.plot(data, label=column) if trend is not None: plt.plot(trend, linewidth=3, label="broad trend") plt.legend() plt.subplot(312) plt.title("detrended") plt.plot(data - trend) else: plt.legend() plt.subplot(312) plt.title("(no detrending specified)") plt.subplot(313) plt.title("periodogram") plt.stem(periods, power) for peak in peaks: period, score, pmin, pmax = peak plt.axvline(period, linestyle='dashed', linewidth=2) plt.axvspan(pmin, pmax, alpha=0.2, color='b') plt.annotate("{}".format(period), (period, score * 0.8)) plt.annotate("{}...{}".format(pmin, pmax), (pmin, score * 0.5)) plt.tight_layout() plt.show()
def try_plot_kmer_spectrum(args): try: import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import json ## final plot name plot_name = os.path.join( args.parent_dir, "stats", "kmer_spectrum.pdf" ) kmer_fn = os.path.join( args.parent_dir, "stats", "histogram_kmer_count.json" ) data = json.loads(open( kmer_fn, "r" ).read()) ## max k-mer multiplicity MAX = 100 if len( data["vals"] ) == 0: martian.log_info ("No kmer data to plot.") return elif len( data["vals"] ) < MAX: martian.log_info ("Warning: no kmers with multiplicity >= %d"%MAX ) MAX = len( data["vals"] ) fig, ax = plt.subplots() #plt.setp(ax.get_yticklabels(), visible=False) ## set mode to 1.0 xvals = range(MAX) yvals = data["vals"][:MAX] ax.plot (xvals, yvals, lw = 2.0, color="blue" ) ## plot tail tail_height = float(sum(data["vals"][MAX:])) _, ymax = plt.ylim() plt.axvspan (xmin=MAX-1, xmax=MAX, ymin=0, ymax=tail_height/ymax, ls=None, color="blue") ## set up axis, grid ax.grid(True) plt.locator_params( 'x', nbins=10 ) plt.locator_params( 'y', nbins=10 ) plt.xlim(0, MAX) yt = ax.get_yticks() ylabels, yexp = nice_labels( yt ) plt.yticks ( yt, ylabels, rotation=45 ) plt.xlabel ( "filtered kmer multiplicity" ) plt.ylabel ( "counts" ) plt.savefig (plot_name) plt.close() except ImportError, e: martian.log_info( "Error importing libraries for plotting" ) martian.log_info( str(e) ) except KeyError, e: martian.log_info( "Invalid key in json while plotting" ) martian.log_info( str(e) ) except IOError, e: martian.log_info( "Could not find the molecule json for plotting" ) martian.log_info( str(e) ) except Exception as e: martian.log_info( "Unexpected error while plotting molecule length") martian.log_info( str(e) )
def plot_events_with_segment_scores(segment_results, ground_truth_events, detected_events, use_datetime_x=False, show=True): """ Test :param segment_results: :param ground_truth_events: :param detected_events: :param use_datetime_x: :param show: :return: """ fig = plt.figure(figsize=(10, 3)) a = 3 # TODO: convert times to datetime if flag is set # write y axis labels for ground truth and detections plt.yticks([0.2, 0.5, 0.8], ["detections", "segment score", "actual events"]) plt.ylim([0, 1]) for d in detected_events: plt.axvspan(d[0], d[1], 0, 0.5) for gt in ground_truth_events: plt.axvspan(gt[0], gt[1], 0.5, 1) for s in segment_results: color = "black" index_of_cat = 4 if s[index_of_cat] == "TP": color = "green" elif s[index_of_cat] == "FP": color = "red" elif s[index_of_cat] == "FN": color = "yellow" elif s[index_of_cat] == "TN": color = "blue" # TODO: format text nicely plt.text((s[1]+s[0])/2, 0.8, s[2], horizontalalignment='center', verticalalignment='center') plt.text((s[1]+s[0])/2, 0.2, s[3], horizontalalignment='center', verticalalignment='center') plt.text((s[1]+s[0])/2, 0.5, s[5], horizontalalignment='center', verticalalignment='center') plt.axvspan(s[0], s[1], 0.4, 0.6, color=color) plt.axvline(s[0], color="black") plt.axvline(s[1], color="black") plt.tight_layout() if show: plt.show() else: plt.draw()
def cb(y, P, counter, current): solution = np.empty(len(y)) for i, (v, w, f, l) in enumerate(P): solution[f:f + l] = (v if i else max(v, 0)) / w * g**np.arange(l) color = y.copy() ax1.plot(solution, c='k', zorder=-11, lw=1.3, clip_on=False) ax1.scatter(np.arange(len(y)), solution, s=40, cmap=plt.cm.Spectral, c=color, clip_on=False, zorder=11) ax1.scatter([np.arange(len(y))[current]], [solution[current]], s=120, lw=2.5, marker='+', color='b', clip_on=False, zorder=11) for a in P[::2]: ax1.axvspan(a[2], a[2] + a[3], alpha=0.1, color='k', zorder=-11) for x in np.where(trueSpikes)[0]: ax1.plot([x, x], [0, 2.3], lw=1.5, c='r', zorder=-12) ax1.set_xlim((0, len(y) - .5)) ax1.set_ylim((0, 2.3)) simpleaxis(ax1) ax1.set_xticks([]) ax1.set_yticks([]) ax1.set_ylabel('Fluorescence') for i, s in enumerate(np.r_[[0], solution[1:] - g * solution[:-1]]): ax2.plot([i, i], [0, s], c='k', zorder=-11, lw=1.4, clip_on=False) ax2.scatter(np.arange(len(y)), np.r_[[0], solution[1:] - g * solution[:-1]], s=40, cmap=plt.cm.Spectral, c=color, clip_on=False, zorder=11) ax2.scatter([np.arange(len(y))[current]], [np.r_[[0], solution[1:] - g * solution[:-1]][current]], s=120, lw=2.5, marker='+', color='b', clip_on=False, zorder=11) for a in P[::2]: ax2.axvspan(a[2], a[2] + a[3], alpha=0.1, color='k', zorder=-11) for x in np.where(trueSpikes)[0]: ax2.plot([x, x], [0, 1.55], lw=1.5, c='r', zorder=-12) ax2.set_xlim((0, len(y) - .5)) ax2.set_ylim((0, 1.55)) simpleaxis(ax2) ax2.set_xticks([]) ax2.set_yticks([]) ax2.set_xlabel('Time', labelpad=35, x=.5) ax2.set_ylabel('Spikes') plt.subplots_adjust(left=0.032, right=.995, top=.995, bottom=0.19, hspace=0.22) if save_figs: plt.savefig('video/%03d.pdf' % counter) plt.pause(1e-9) ax1.clear() ax2.clear() # generate data
def residualPlots(datas, residuals, saveAs, ROI = None, xdat = None, pltRange = None): '''@brief Generates a set of plots and residuals. @param datas Zipped data arrays and legend titles @param residuals Zipped array of residuals and legend titles @param saveAs Filename to save plot as @param ROI Optional parameter specifying region of interest in the plot @param xdat Optional zipped array of x values and titles. Defaults to iteration values. @param pltRange Optional specified plot range. ''' if xdat is None: xvals = range(len(datas[0][0])) xlabel = "Iteration" else: xvals, xlabel = xdat fig1 = plt.figure(1) frame1 = fig1.add_axes((.1, .3, .8, .6)) for data, legtitle in datas: plt.plot(xvals, data, label = legtitle) # legendtitles = [legtitle for data, legtitle in datas] if pltRange is not None: plt.ylim(pltRange) plt.legend(loc = 'upper left', prop = {'size': 8}) frame1.set_xticklabels([]) # Remove x-tic labels for the first frame plt.grid() # ROI if ROI is not None: plt.axvspan(ROI[0], ROI[1], facecolor = '0.5', alpha = 0.5) plt.text(np.mean(ROI), frame1.get_ylim()[1] * .9, "ROI") # Residual plot frame2 = fig1.add_axes((.1, .1, .8, .2)) for data, legtitle in residuals: plt.plot(xvals, data, 'o', label = legtitle) # legendtitles = [legtitle for data, legtitle in residuals] plt.legend(loc = 'upper left', prop = {'size': 8}) plt.xlabel(xlabel) plt.grid() # ROI for second subplot if ROI is not None: plt.axvspan(ROI[0], ROI[1], facecolor = '0.5', alpha = 0.5) # plt.text(np.mean(ROI), frame1.get_ylim()[1]*.9, "ROI") # Render to image fig1.savefig(saveAs) plt.close()
def plot_spike_sources(filePath, fileName, nrInputNeurons, nrVR, observationTime, totalSimulationTime, classLabels, odourNames): '''Plot the Poisson spike source matrix Input: -path of the spike times file -name of the spike times file -number of input neurons (= number of sensors) -number of virtual receptors -length of the Poisson spike train for each sample -maximum simulation time for each recording (number of samples for each recording) x (length of Poisson spike train for each sample) -class labels -names of the odours used ''' bckndNames =[[]]*len(odourNames) spikeTimes = utils.readSpikeSourceDataFile(os.path.join(filePath, fileName))['spike_times'] plt.figure(figsize=(20,20)) for idx, line in enumerate(spikeTimes): for x in line: plt.plot(x, idx, 'ko', markersize = 2) for j in range(idx, nrVR): plt.plot(0, j, 'k,') for j, classLabel in enumerate(classLabels): plt.axvspan(j*observationTime, j*observationTime+observationTime, facecolor=colors[int(classLabel)], alpha=0.3) for idxO, odour in enumerate(odourNames): bckndNames[idxO] = mpatches.Patch(color=colors[idxO], label=odour) plt.legend(handles=bckndNames, loc ='best', prop={'size':20}) plt.xlabel('Simulation time[ms]', fontsize=20) plt.ylabel('%i Virtual receptors per sensor'%(nrVR/nrInputNeurons), fontsize=20) plt.tick_params(labelsize=20) plt.title('VR spike times for classes %s'%str(classLabels), fontsize=20) plt.savefig(fileName+'.pdf') plt.close() #-----------------------------------------------------------------------------
def _pre_fitting_plots(self, cum_dose_left, z_fitting_cm_1d, dose_fitting_MeV_g_1d, threshold, zmax_cm): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt prefix = os.path.join(self.outputdir, 'ddd_{:3.1f}MeV_'.format(self.energy_MeV)) plt.plot(self.z_data_cm_1d, self.dose_data_MeV_g_1d, color='blue', label='dose') plt.axvspan( 0, zmax_cm, alpha=0.1, color='green', label="fitting area, covers {:g} % of dose".format(100.0 * (1 - threshold))) plt.legend(loc=0) plt.xlabel('z [cm]') plt.ylabel('dose [a.u.]') if self.verbosity > 1: out_filename = prefix + 'dose_all.png' logger.info('Saving ' + out_filename) plt.savefig(out_filename) plt.yscale('log') out_filename = prefix + 'all_log.png' logger.info('Saving ' + out_filename) plt.savefig(out_filename) plt.close() if self.verbosity > 1: bp_max_z_pos_cm = self.z_data_cm_1d[self.dose_data_MeV_g_1d == self.dose_data_MeV_g_1d.max()] plt.semilogy(self.z_data_cm_1d, cum_dose_left, color='blue', label="cumulative missing dose") plt.axvspan( 0, zmax_cm, alpha=0.1, color='green', label="fitting area, covers {:g} % of dose".format(100.0 * (1 - threshold))) plt.axhline(threshold, color='black', label='threshold {:g}'.format(threshold)) plt.axvline(bp_max_z_pos_cm, color='red', label='BP max') plt.legend(loc=0) plt.xlabel('z [cm]') plt.ylabel('fraction of total dose deposited behind z') out_filename = prefix + 'dose_frac.png' logger.info('Saving ' + out_filename) plt.savefig(out_filename) plt.close() if self.verbosity > 1: plt.plot(z_fitting_cm_1d, dose_fitting_MeV_g_1d, 'b', label='dose') plt.xlabel('z [cm]') plt.ylabel('dose [MeV/g]') plt.yscale('log') out_filename = prefix + 'dose_log.png' logger.info('Saving ' + out_filename) plt.savefig(out_filename) plt.close()