我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用matplotlib.pyplot.figtext()。
def plot_it(x, arr_y, labels=None, fname=None, figtext='', loc=1): if labels is not None: assert len(arr_y) == len(labels) else: labels = [None] * len(arr_y) plt.figure() plt.gca().set_position((.1, .3, .8, .7)) # to make a bit of room for extra text for y,lab in zip(arr_y, labels): plt.errorbar(x, y[:,0], yerr=y[:,1], fmt='-o', label=lab) plt.legend(loc=loc) plt.xlim((-1, 30)) #plt.figtext(0,0,figtext) #plt.plot(x, y[:,2], '-o', label='median') plt.figtext(.02, .02, figtext,fontsize=16) plt.xlabel("% skipped") if fname is not None: plt.savefig(fname, bbox_inches='tight') plt.clf() else: plt.show()
def runobsplot(self): """ A quick histogram to see that intrinsic variance compared to the initial estimate """ tdmin = self.iniest.td - 3.0*self.iniest.tderr tdmax = self.iniest.td + 3.0*self.iniest.tderr fig = plt.figure(figsize=(6, 3)) fig.subplots_adjust(top=0.95, bottom=0.2) if len(self.obsmesdelays) != 0: plt.hist(self.obsmesdelays, range=(tdmin, tdmax), bins=200, color="green", lw=0) plt.xlim(tdmin, tdmax) plt.xlabel("Delay [day]") plt.ylabel("Counts") #ax = plt.gca() plt.figtext(0.15, 0.8, "Intrinsic/initial error ratio: %.2f" % self.intrinsicratio) plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axvline(self.outest.td, color="red", linestyle="-", zorder=20) plt.savefig(os.path.join(self.plotdir, "intrinsic_variance.png")) plt.close()
def update_plot(self): layers = self.get_trainable_layers() for layer in layers: for param in self.parameters: weights = [w for w in layer.weights if param in w.name.split("_")] if len(weights) == 0: continue val = numpy.column_stack((w.get_value() for w in weights)) name = layer.name + "_" + param self.layers_stats[name]["values"] = val.ravel() for s in self.stats: if s == "raster": if len(val.shape) > 2: val = val.reshape((val.shape[0], -1), order='F') self.layers_stats[name][s] = val # self.fig.colorbar() else: self.layers_stats[name][s].append( getattr(numpy, s)(val)) plt.figtext(.02, .02, get_model_desc(self.model), wrap=True, fontsize=8) self.fig.tight_layout() self.fig.subplots_adjust(bottom=.2) self.fig.canvas.draw() self.fig.canvas.flush_events()
def plot(self, path): """ :param path: :return: """ self.run() with warnings.catch_warnings(): warnings.simplefilter('ignore') with PdfPages(path) as pdf: for i, tup in enumerate(zip(self.V, self.e)): V, e = tup if V is not None: V.plot(); plt.subplots_adjust(right=0.7) plt.figtext(0.73, 0.73, '%s: %.2f' % (self.eval, e), fontsize=14) plt.figtext(0.73, 0.45, str(V), fontsize=10) plt.figtext(0.73, 0.29, '\n'.join(['%s: %s' % (n, str(v)) for n,v in zip(self.names, self.combinations[i]) ]), fontsize=10) pdf.savefig(plt.gcf()) else: f,ax = plt.subplot(1,1) plt.figtext(1, 0.73, 'No Result for combination: ', fontsize=14) plt.figtext(0.1, 0.45, '\n'.join(['%s: %s' % (n, str(v)) for n,v in zip(self.names, self.combinations[i]) ]), fontsize=10) pdf.savefig() if self.verbose: sys.stdout.write('%d/%d plots drawn.\n' % (i+1, self.n))
def plot(lc1, lc2, timewidth=30, timestep=1.0, optml=False): """ Interactively plot a timeshift spectrum. """ # We prepare the timeshifts to explore timeshifts = np.arange(-(timewidth)*timestep/2.0, (timewidth+1)*timestep/2.0, timestep) print "Exploring timeshifts from %f to %f" % (timeshifts[0], timeshifts[-1]) # This corresponds to the following actual time delays : timedelays = timeshifts + lc2.timeshift - lc1.timeshift print "... that is time delays from %f to %f"% (timedelays[0], timedelays[-1]) # We calculate the spectra : spectrum = timeshift(lc1, lc2, timeshifts) # And show all this in a plot : fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(timedelays, spectrum, "r.") ax1.set_ylabel("chi2") ax1.set_xlabel("Time delay of %s with respect to %s [days]" % (lc1.object, lc2.object)) #for tl in ax1.get_yticklabels(): # tl.set_color('r') #ax2 = ax1.twinx() #ax2.plot(timedelays, spectrum["n"], "b.") #for tl in ax2.get_yticklabels(): # tl.set_color('b') #ax2.set_ylabel("Number of terms") # this causes a crash, probably a bug... #plt.figtext(0.13, 0.9, "Magnitude shift of %s with respect to %s : %6.4f" % (lc2.object, lc1.object, lc2.magshift - lc1.magshift)) plt.figtext(0.14, 0.96, "%s" % (str(lc1))) plt.figtext(0.14, 0.93, "versus") plt.figtext(0.14, 0.90, "%s" % (str(lc2))) plt.show()
def runsimplot(self): """ Viz of the MC results """ tdmin = self.iniest.td - 3.0*self.iniest.tderr tdmax = self.iniest.td + 3.0*self.iniest.tderr fig = plt.figure(figsize=(6, 3)) fig.subplots_adjust(top=0.95, bottom=0.2) plt.scatter(self.simtruedelays, self.simmesdelays - self.simtruedelays) plt.xlim(tdmin, tdmax) plt.xlabel("True delay [day]") plt.ylabel("Measurement error [day]") plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhline(0, color="black", linestyle="-", zorder=20) plt.axhline(- self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhline(+ self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhspan(-self.outest.tderr, self.outest.tderr, xmin=0, xmax=1, lw=0, color="red", alpha=0.2) #plt.ylim(- 2.0*self.iniest.tderr, + 2.0*self.iniest.tderr) plt.figtext(0.15, 0.8, "Total/initial error ratio: %.2f" % self.totalratio) #ax = plt.gca() #plt.figtext(0.15, 0.8, "Intrinsic/initial error ratio: %.2f" % self.intrinsicratio) #plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) #plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) #plt.axvline(self.outest.td, color="red", linestyle="-", zorder=20) plt.savefig(os.path.join(self.plotdir, "measvstrue.png")) plt.close()
def plot_with_labels(low_dim_embs,labels,filename=plt_dir): plt.figure(figsize=(10,10)) for i,label in enumerate(labels): x,y=low_dim_embs[i,:] plt.scatter(x,y) plt.annotate(label,xy=(x,y),xytext=(5,2), textcoords="offset points", ha="right", va="bottom") f_text="vocabulary_size=%d;batch_size=%d;embedding_size=%d;skip_window=%d;num_iter=%d"%( vocabulary_size,batch_size,embedding_size,skip_window,num_iter ) plt.figtext(0.03,0.03,f_text,color="green",fontsize=10) plt.show() plt.savefig(filename)
def plot_with_labels(low_dim_embs,labels,filename=plt_dir): plt.figure(figsize=(10,10)) for i,label in enumerate(labels): x,y=low_dim_embs[i,:] plt.scatter(x,y) plt.annotate(label,xy=(x,y),xytext=(5,2), textcoords="offset points", ha="right", va="bottom") f_text="vocabulary_size=%d;batch_size=%d;embedding_size=%d;num_skips=%d;skip_window=%d;num_steps=%d"%( vocabulary_size,batch_size,embedding_size,num_skips,skip_window,num_steps ) plt.figtext(0.03,0.03,f_text,color="green",fontsize=10) plt.show() plt.savefig(filename)
def reset(self): self.fig.clf() ax = self.fig.add_subplot(111) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) ax.axis(np.add(ax.axis(), [-.5, .5, -.5, .5])) ax.axis('off') self.ax = ax self.txt = plt.figtext(0.5, 0.1, "", horizontalalignment='center', wrap=True) self.scenes = []
def __call__(self, i): if i == 0: self.txt = plt.figtext(0.5, 0.5, self.text, horizontalalignment='center', wrap=True) if i > 0: self.txt.set_color(str((i + 1) / self.anim.fps)) if i == self.anim.fps - 1: self.txt.set_text("") plt.draw() return self.txt,
def gen_depthwise(): gtx_ = np.asarray(gtx[:,0:2]).transpose() tx1_ = np.asarray(tx1[:,0:2]).transpose() tk1_ = np.asarray(tk1[:,0:2]).transpose() raspi_ = np.asarray(raspi[:,0:2]).transpose() out = [gtx_, tx1_, tk1_, raspi_] for i in range(len(platform_dd)): plt.ylabel('log time per image(ms)') plt.yscale('log') plt.ylim([0.5, 300*10**(i+1) + 8**(i+1)]) #manipulating axis plt.xlabel('batch size') plt.xscale('log') plt.xlim([0.5,256]) plt.xticks(x_dd,x_dd) plt.figtext(.5,.93,platform_dd[i], fontsize=18, ha='center') plt.figtext(.5,.9,'mobilenet improvement by depthwise convolution',fontsize=10,ha='center') plt.minorticks_off() line = plt.plot(x_dd,out[i][0],'--o', label='mobilenet') line1 = plt.plot(x_dd,out[i][1],'--o', label='mobilenet depthwise') plt.legend() #plt.show() plt.savefig('mobilenet_'+platform_dd[i]+'.png', bbox_inches='tight') plt.clf() plt.close() ##run stuff here #gen_platform() #gen_cost() #gen_small_cost() #gen_depthwise()
def draw_histograms(packets_all_hosts, histogram_merge_all_files, skip_slow_analyses, cutoff_time_ms, save_dir, output_postfix): """ Draw histograms of packet latency. """ if histogram_merge_all_files: packet_data = graph_common.merge_all_hosts(packets_all_hosts) else: packet_data = packets_all_hosts bins_log_scale = graph_common.calculate_histogram_bins(packet_data) n_result_sets = len(packet_data) plt.figure(figsize=(10, 6)) plt.suptitle("Packet latency histograms") text_vertical_spacing = 1.0 / n_result_sets for result_set_n in range(n_result_sets): (filename, packet_ns, latencies_ms, total_n_packets) = packet_data[result_set_n] plt.subplot(n_result_sets, 1, result_set_n + 1) plt.title(filename) last_plot = (result_set_n == (n_result_sets - 1)) if last_plot: xlabel = True else: xlabel = False graph_common.draw_histogram(latencies_ms, bins_log_scale, cutoff_time_ms, xlabel) y = 1 - result_set_n * text_vertical_spacing - 0.5 * text_vertical_spacing text = gen_histogram_text(packet_ns, latencies_ms, total_n_packets, cutoff_time_ms, skip_slow_analyses) plt.figtext(0.55, y, text, verticalalignment='center') plt.tight_layout() plt.subplots_adjust(top=0.9) # to make room for suptitle plt.subplots_adjust(right=0.5) plot_filename = os.path.join(save_dir, 'udp_latency_histogram%s.png' % output_postfix) plt.savefig(plot_filename)
def draw_plot(self): self.fig.clf() layers = self.get_trainable_layers() height = len(self.layers_stats) width = len(self.stats) + 1 plot_count = 1 for layer in layers: for param in self.parameters: weights = [w for w in layer.weights if param in w.name.split("_")] if len(weights) == 0: continue val = numpy.column_stack((w.get_value() for w in weights)) name = layer.name + "_" + param self.layers_stats[name]["values"] = val.ravel() ax = self.fig.add_subplot(height, width, plot_count) ax.hist(self.layers_stats[name]["values"], bins=50) ax.set_title(name, fontsize=10) ax.grid(True) ax.tick_params(labelsize=8) plot_count += 1 for s in self.stats: axs = self.fig.add_subplot(height, width, plot_count) if s == "raster": if len(val.shape) > 2: val = val.reshape((val.shape[0], -1), order='F') self.layers_stats[name][s] = val m = axs.imshow(self.layers_stats[name][s], cmap='coolwarm', interpolation='nearest', aspect='auto', ) # aspect='equal' cbar = self.fig.colorbar(mappable=m) cbar.ax.tick_params(labelsize=8) else: self.layers_stats[name][s].append( getattr(numpy, s)(val)) axs.plot(self.layers_stats[name][s]) axs.set_ylabel(s, fontsize="small") axs.set_xlabel('epoch', fontsize="small") axs.grid(True) axs.set_title(name + " - " + s, fontsize=10) axs.tick_params(labelsize=8) plot_count += 1 # plt.figtext(.1, .1, get_model_desc(self.model), wrap=True, fontsize=8) desc = get_model_desc(self.model) self.fig.text(.02, .02, desc, verticalalignment='bottom', wrap=True, fontsize=8) self.fig.tight_layout() self.fig.subplots_adjust(bottom=.14) self.fig.canvas.draw() self.fig.canvas.flush_events()
def average_gt_classes(fn): with open(fn) as f: line_count = 0 num_actual_list = [] num_pred_list = [] scores = [] for line in f: if line_count % 10000 == 0: print("Number of lines evaluated: {}").format(line_count) words = line.strip().split(',') words = [x.strip() for x in words] num_actual = int(words[1]) if num_actual > 50: print num_actual num_actual_list.append(num_actual) num_pred = int(words[(2+num_actual)]) num_pred_list.append(num_pred) actual = words[2:(2+num_actual)] preds = words[(3+num_actual):] scores.append(apk(actual, preds, 1001)) line_count += 1 sum_actual = sum(num_actual_list) sum_preds = sum(num_pred_list) avg_pred = float(sum_preds)/line_count avg_actual = float(sum_actual)/line_count print "Average actual: ", avg_actual print "Average pred: ", avg_pred print "Mean average precision: ", round(np.mean(scores), 4) * 100 # Calculate average score for plots: x, y = zip(*sorted((xVal, np.mean([yVal for a, yVal in zip(num_pred_list, scores) if xVal==a])) for xVal in set(num_pred_list))) import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt print num_actual plt.ylabel('Average Precision') plt.xlabel('Number of actual') plt.plot(x, y, 'r-', linewidth=2) plt.figtext(.8, .8, "Average actual: " + str(avg_actual)) plt.figtext(.8, .75, "Average predicted: " + str(avg_pred)) plt.axis([0, 25, 0, 0.5]) #plt.show() from matplotlib2tikz import save as tikz_save tikz_save('test.tex')
def display_triplet_distance_test(model,test_loader,name): f, axarr = plt.subplots(5,2,figsize=(10,10)) f.tight_layout() l2_dist = PairwiseDistance(2) for batch_idx, (data_a, data_n,label) in enumerate(test_loader): if np.all(label.cpu().numpy()): continue try: data_a_c, data_n_c = data_a.cuda(), data_n.cuda() data_a_v, data_n_v = Variable(data_a_c, volatile=True), \ Variable(data_n_c, volatile=True) out_a, out_n = model(data_a_v), model(data_n_v) except Exception as ex: print(ex) print("ERROR at: {}".format(batch_idx)) break for i in range(5): rand_index = np.random.randint(0, label.size(0)-1) if i%2 == 0: for j in range(label.size(0)): # Choose label == 0 rand_index = np.random.randint(0, label.size(0)-1) if label[rand_index] == 0: break distance = l2_dist.forward(out_a,out_n).data[rand_index][0] print("Distance: {}".format(distance)) #distance_pca = l2_dist.forward(PCA(128).fit_transform(out_a.data[i].cpu().numpy()),PCA(128).fit_transform(out_n.data[i].cpu().numpy())).data[0] #print("Distance(PCA): {}".format(distance_pca)) axarr[i][0].imshow(denormalize(data_a[rand_index])) axarr[i][1].imshow(denormalize(data_n[rand_index])) plt.figtext(0.5, i/5.0+0.1,"Distance : {}, Label: {}\n".format(distance,label[rand_index]), ha='center', va='center') break plt.subplots_adjust(hspace=0.5) f.savefig("{}.png".format(name)) #plt.show()
def zipf(self, clusters_org='source'): ''' Zipf Analysis Local/Global Preferential attachment effect analysis Parameters ---------- clusters_org: str cluster origin if from either ['source'|'model'] ''' expe = self.expe frontend = FrontendManager.load(expe) # # Get the Class/Cluster and local degree information # Reordering Adjacency Mmatrix based on Clusters/Class/Communities # clusters = None K = None if clusters_org == 'source': clusters = frontend.get_clusters() elif clusters_org == 'model': model = ModelManager.from_expe(expe) #clusters = model.get_clusters(K, skip=1) #clusters = model.get_communities(K) clusters = Louvain.get_clusters(frontend.to_directed(), resolution=10) if len(np.unique(clusters)) > 20 or False: self.log.info('Using Annealing clustering') clusters = Annealing(frontend.data, iterations=200, C_init=5, grow_rate=0).search() else: self.log.info('Using Louvain clustering') if clusters is None: lgg.error('No clusters here...passing') return else: block_hist = np.bincount(clusters) K = (block_hist != 0).sum() lgg.info('%d Clusters from `%s\':' % (K, clusters_org)) data_r = reorder_mat(frontend.data, clusters) np.fill_diagonal(data_r, 0) from pymake.util.math import dilate dlt = lambda x : dilate(x) if x.sum()/x.shape[0]**2 < 0.1 else x ### Plot Adjacency matrix fig, (ax1, ax2) = plt.subplots(1,2) fig.tight_layout(pad=1.6) adjshow(dlt(data_r), title=self.specname(expe.corpus), ax=ax1) #plt.figtext(.15, .1, homo_text, fontsize=12) #plt.suptitle(self.specname(expe.corpus)) ### Plot Degree plot_degree_poly(data_r, ax=ax2) if expe.write: self.write_figs(expe, [fig], _suffix='dd')
def topoplot_snr(self, collapse_epochs=True, flims='stimulation', **kwargs): """ Plot the signal-to-noise-ratio-spectrum across the scalp. Parameters: collapse_epochs : bool Whether you want to plot the average of all epochs (default), or each power-spectrum individually. flims : list | str Which frequency bands you want to plot. By default, the stimulation frequencies will be plotted. Can be limits (eg. [6, 8]) or a string referring to an evoked frequency (eg. 'stimulation', 'harmonic') """ # Find out over which range(s) to collapse: fmins, fmaxs = self._get_flims(flims) if len(fmins.flatten()) > 1: topodata = [np.stack([self._get_snr(freq) for freq in self.freqs if freq > fmin and freq < fmax], axis=-1).mean(-1) for fmin, fmax in zip(fmins.flatten(), fmaxs.flatten())] annot = [(str(fmin) + ' - ' + str(fmax) + ' Hz') for fmin, fmax in zip(fmins.flatten(), fmaxs.flatten())] if collapse_epochs: topodata = [t.mean(axis=0) for t in topodata] else: topodata = np.stack([self._get_snr(freq) for freq in self.freqs if freq > fmins and freq < fmaxs], axis=-1).mean(-1) # annotation annot = (str(fmins[0]) + ' - ' + str(fmaxs[0]) + ' Hz') if collapse_epochs: topodata = topodata.mean(axis=0) self._plot_topo(topodata, annot, **kwargs) plt.gca() plt.suptitle('SNR', size='xx-large') # plt.figtext(0.05, 0.05, annot, # size='small') plt.show()
def _plot_topo(info, times, show_func, click_func=None, layout=None, vmin=None, vmax=None, ylim=None, colorbar=None, border='none', axis_facecolor='k', fig_facecolor='k', cmap='RdBu_r', layout_scale=None, title=None, x_label=None, y_label=None, font_color='w', unified=False, img=False): """Helper function to plot on sensor layout""" import matplotlib.pyplot as plt # prepare callbacks tmin, tmax = times[[0, -1]] click_func = show_func if click_func is None else click_func on_pick = partial(click_func, tmin=tmin, tmax=tmax, vmin=vmin, vmax=vmax, ylim=ylim, x_label=x_label, y_label=y_label, colorbar=colorbar) fig = plt.figure() if colorbar: norm = normalize_colors(vmin=vmin, vmax=vmax) sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array(np.linspace(vmin, vmax)) ax = plt.axes([0.015, 0.025, 1.05, .8], axisbg=fig_facecolor) cb = fig.colorbar(sm, ax=ax) cb_yticks = plt.getp(cb.ax.axes, 'yticklabels') plt.setp(cb_yticks, color=font_color) ax.axis('off') my_topo_plot = _iter_topography(info, layout=layout, on_pick=on_pick, fig=fig, layout_scale=layout_scale, axis_spinecolor=border, axis_facecolor=axis_facecolor, fig_facecolor=fig_facecolor, unified=unified, img=img) for ax, ch_idx in my_topo_plot: if layout.kind == 'Vectorview-all' and ylim is not None: this_type = {'mag': 0, 'grad': 1}[channel_type(info, ch_idx)] ylim_ = [v[this_type] if _check_vlim(v) else v for v in ylim] else: ylim_ = ylim show_func(ax, ch_idx, tmin=tmin, tmax=tmax, vmin=vmin, vmax=vmax, ylim=ylim_) if title is not None: plt.figtext(0.03, 0.9, title, color=font_color, fontsize=19) return fig