我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用matplotlib.pyplot.cla()。
def vis_detections(im, class_name, dets, thresh=0.3): """Visual debugging of detections.""" import matplotlib.pyplot as plt im = im[:, :, (2, 1, 0)] for i in xrange(np.minimum(10, dets.shape[0])): bbox = dets[i, :4] score = dets[i, -1] if score > thresh: plt.cla() plt.imshow(im) plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='g', linewidth=3) ) plt.title('{} {:.3f}'.format(class_name, score)) plt.show()
def create_graph(): logfile = 'result/log' xs = [] ys = [] ls = [] f = open(logfile, 'r') data = json.load(f) print(data) for d in data: xs.append(d["iteration"]) ys.append(d["main/accuracy"]) ls.append(d["main/loss"]) plt.clf() plt.cla() plt.hlines(1, 0, np.max(xs), colors='r', linestyles="dashed") # y=-1, 1?????? plt.title(r"loss/accuracy") plt.plot(xs, ys, label="accuracy") plt.plot(xs, ls, label="loss") plt.legend() plt.savefig("result/log.png")
def plot2d_simplex(simplex, ind): fig_dir = "./" plt.cla() n = 1000 x1 = np.linspace(-256, 1024, n) x2 = np.linspace(-256, 1024, n) X, Y = np.meshgrid(x1, x2) Z = np.sqrt(X ** 2 + Y ** 2) plt.contour(X, Y, Z, levels=list(np.arange(0, 1200, 10))) plt.gca().set_aspect("equal") plt.xlim((-256, 768)) plt.ylim((-256, 768)) plt.plot([simplex[0].x[0], simplex[1].x[0]], [simplex[0].x[1], simplex[1].x[1]], color="#000000") plt.plot([simplex[1].x[0], simplex[2].x[0]], [simplex[1].x[1], simplex[2].x[1]], color="#000000") plt.plot([simplex[2].x[0], simplex[0].x[0]], [simplex[2].x[1], simplex[0].x[1]], color="#000000") plt.savefig(os.path.join(fig_dir, "{:03d}.png".format(ind)))
def fast_run(args): model = Model(args) feed = {} #feed[model.train_batch]=False xx,ss,yy=model.inputs(args.input_path) sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) tf.train.start_queue_runners(sess=sess) xxx,sss,yyy=sess.run([xx,ss,yy]) #print(yyy) #print(yyy[1]) print('len:',xxx.shape) import matplotlib.cm as cm import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt plt.figure(figsize=(16,4)) #plt.imshow() plt.imshow(np.asarray(xxx[0]).reshape((36,90))+0.5, interpolation='nearest', aspect='auto', cmap=cm.jet) plt.savefig("img.jpg") plt.clf() ; plt.cla()
def draw(vmean, vlogstd): from scipy import stats plt.cla() xlimits = [-2, 2] ylimits = [-4, 2] def log_prob(z): z1, z2 = z[:, 0], z[:, 1] return stats.norm.logpdf(z2, 0, 1.35) + \ stats.norm.logpdf(z1, 0, np.exp(z2)) plot_isocontours(ax, lambda z: np.exp(log_prob(z)), xlimits, ylimits) def variational_contour(z): return stats.multivariate_normal.pdf( z, vmean, np.diag(np.exp(vlogstd))) plot_isocontours(ax, variational_contour, xlimits, ylimits) plt.draw() plt.pause(1.0 / 30.0)
def show_boxes(im, dets, classes, scale = 1.0): plt.cla() plt.axis("off") plt.imshow(im) for cls_idx, cls_name in enumerate(classes): cls_dets = dets[cls_idx] for det in cls_dets: bbox = det[:4] * scale color = (rand(), rand(), rand()) rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor=color, linewidth=2.5) plt.gca().add_patch(rect) if cls_dets.shape[1] == 5: score = det[-1] plt.gca().text(bbox[0], bbox[1], '{:s} {:.3f}'.format(cls_name, score), bbox=dict(facecolor=color, alpha=0.5), fontsize=9, color='white') plt.show() return im
def plot_Vavg(self,Vavg,Vbias,offset=None,axes=None): Iavg=self.ADU2I(Vavg,offset) lbl=str('V$_{bias}$ = %.2fV' % Vbias) plt.cla() if isinstance(axes,list) or isinstance(axes,np.ndarray): plt.axis(axes) plt.xlabel('TES number') plt.ylabel('I / $\mu$A') # plot markers with no lines plt.plot(Iavg,marker='D',drawstyle='steps-mid',linestyle='none',color='green',label=lbl) # plot bars up to the markers tes_axis=np.arange(self.NPIXELS)-0.25 plt.bar(tes_axis,height=Iavg,color='pink',width=0.5) plt.legend() plt.pause(0.01) return
def vis_detections(im, class_name, dets, thresh=0.5): """Visual debugging of detections.""" im = im[:, :, (2, 1, 0)] for i in xrange(np.minimum(5, dets.shape[0])): bbox = dets[i, :4] score = dets[i, -1] if score > thresh: plt.cla() plt.imshow(im) plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='g', linewidth=3) ) plt.title('{} {:.3f}'.format(class_name, score)) plt.show()
def visualize_scores(avg_scores, ind_scores_over_time, trs, name): """ Visualizes the validation Jaccard Scores for all ten classes over the epochs. """ plt.plot(avg_scores, lw=3) for z in range(10): plt.plot(ind_scores_over_time[z], ls="--") plt.title('Jaccard Scores') plt.ylabel('Score') plt.xlabel('Epoch') legend = plt.legend(["Avg Score", "Buildings", "Structures", "Road", "Track", "Trees", "Crops", "Waterway", "Standing Water", "Trucks", "Cars"], loc='upper left', frameon=True) frame = legend.get_frame() frame.set_facecolor('white') os.makedirs("../plots", exist_ok=True) plt.savefig("../plots/scores_{}.png".format(name), bbox_inches="tight", pad_inches=1) plt.clf() plt.cla() plt.close()
def vis_detections(im, class_name, dets, thresh=0.8): """Visual debugging of detections.""" import matplotlib.pyplot as plt #im = im[:, :, (2, 1, 0)] for i in xrange(np.minimum(10, dets.shape[0])): bbox = dets[i, :4] score = dets[i, -1] if score > thresh: #plt.cla() #plt.imshow(im) plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='g', linewidth=3) ) plt.gca().text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') plt.title('{} {:.3f}'.format(class_name, score)) #plt.show()
def show_boxes(im, dets, classes, scale = 1.0): plt.cla() plt.axis("off") plt.imshow(im) for cls_idx, cls_name in enumerate(classes): cls_dets = dets[cls_idx] for det in cls_dets: bbox = det[:4] * scale color = (random.random(), random.random(), random.random()) rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor=color, linewidth=2.5) plt.gca().add_patch(rect) if cls_dets.shape[1] == 5: score = det[-1] plt.gca().text(bbox[0], bbox[1], '{:s} {:.3f}'.format(cls_name, score), bbox=dict(facecolor=color, alpha=0.5), fontsize=9, color='white') plt.show() return im
def post_graph(self, error, prediction): self.plot_points.append((self.iteration, error)) # Error plot plt.subplot(1, 2, 1) plt.cla() plt.title('Error') plt.plot(*zip(*self.plot_points), marker='.', color=(.9148, .604, .0945)) # Environment plot plt.subplot(1, 2, 2) plt.cla() plt.title('Environment') self.environment.plot(plt, prediction) plt.pause(0.00001)
def plot(self, sort_csv_file, forecast_csv_file, save_fig_file): sort_df = pd.read_csv(sort_csv_file) sort_df['date'] = pd.to_datetime(sort_df['date'], format='%Y-%m-%d') sort_df = sort_df.set_index(pd.DatetimeIndex(sort_df['date'])) forecast_df = pd.read_csv(forecast_csv_file, header=None, names=['date', 'aver']) forecast_df['date'] = pd.to_datetime(forecast_df['date'], format='%Y-%m-%d') forecast_df = forecast_df.set_index(pd.DatetimeIndex(forecast_df['date'])) forecast_df['aver'].plot(figsize=(20, 20), c='r', linewidth=3.0) ax = sort_df['aver'].plot(figsize=(20, 20), linewidth=3.0) plt.ylabel('price') plt.xlabel('date') ax.set_ylim(sort_df['aver'].min() * 0.8, sort_df['aver'].max() * 1.2) plt.savefig(save_fig_file) plt.cla() plt.clf() plt.close()
def lineplot(gcfreqdict): namelist = [] i = -1 xlist = ['1', '2', '4', '8', '16', '32', '48'] ylist = [] for name in gcfreqdict: i += 1 ylist = [] namelist.append(name) base = gcfreqdict[name][0] for gc in gcfreqdict[name]: ylist.append(float(gc/base)) plt.figure(0) plt.plot(range(len(ylist)), ylist, marker=markerlist[i], color='#d3d3d3',label=name) plt.savefig("GC_Frequency.pdf", format='pdf', bbox_inches='tight') plt.figure(0) plt.xticks(range(len(xlist)), xlist) plt.ylabel("Number of GC") plt.xlabel("Benchmarks run with different processor cores number") plt.legend(loc="upper left", ncol=3) plt.savefig("GC_Frequency.pdf", format='pdf', bbox_inches='tight') plt.cla()
def save_plot(file, eta): # axes between 0 and 1 ax.set_xlim3d(0, 1) ax.set_ylim3d(0, 1) ax.set_zlim3d(0, 1) # remove tick marks ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) # title # plt.title("$\eta$ = %.2f" % eta) # save plot plt.savefig("plots/%s.jpg" % file) plt.close() # clear for next plot plt.cla() return
def save_plot(file, eta): # axes between 0 and 1 plt.axis([0,1,0,1]) # remove tick marks frame = plt.gca() frame.axes.get_xaxis().set_ticks([]) frame.axes.get_yaxis().set_ticks([]) # title plt.title("$\eta$ = %.2f" % eta) # save plot plt.savefig("plots/%s.jpg" % file[10:-4]) plt.close() # clear for next plot plt.cla() return
def test_cdf_plot(artworks_df, artworks_summary): column = 'Height (cm)' plt.cla() def mock_render(fig): ax = fig.axes[0] assert len(ax.lines) == 1 line = ax.lines[0] tdigest = artworks_summary.tdigest(column) xs = [tdigest.percentile(p) for p in [0, 100]] assert line.get_xdata()[0] == xs[0] assert line.get_xdata()[-1] == xs[-1] assert line.get_ydata()[0] == 0 assert line.get_ydata()[-1] == 100 explorer = Explorer(artworks_summary, plot_renderer=mock_render) explorer.cdf_plot('Height (cm)')
def vis_detections(im, class_name, dets, thresh=0.8): """Visual debugging of detections.""" import matplotlib.pyplot as plt #im = im[:, :, (2, 1, 0)] for i in range(np.minimum(10, dets.shape[0])): bbox = dets[i, :4] score = dets[i, -1] if score > thresh: #plt.cla() #plt.imshow(im) plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='g', linewidth=3) ) plt.gca().text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') plt.title('{} {:.3f}'.format(class_name, score)) #plt.show()
def calculate_histogram(self): slice = self.pick_slice.value() ax = self.figure.add_subplot(111) ax.hold(False) plt.cla() n_channels = len(self.zcoord) hues = np.arange(0, 1, 1 / n_channels) self.colors = [colorsys.hsv_to_rgb(_, 1, 1) for _ in hues] self.bins = np.arange(np.amin(np.hstack(self.zcoord)),np.amax(np.hstack(self.zcoord)),slice) self.patches = [] ax.hold(True) for i in range(len(self.zcoord)): n, bins, patches = plt.hist(self.zcoord[i], self.bins, normed=1, facecolor=self.colors[i], alpha=0.5) self.patches.append(patches) plt.xlabel('Z-Coordinate [nm]') plt.ylabel('Counts') plt.title(r'$\mathrm{Histogram\ of\ Z:}$') # refresh canvas self.canvas.draw() self.sl.setMaximum(len(self.bins)-2) #self.sl.setValue(np.ceil((len(self.bins)-2)/2))
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 misclassifications(file_names, img_path, y_true, y_pred, classes, out_dir, n=10): class_count = [0] * (np.max(y_true) + 1) fig, ax = plt.subplots() classes = dict_reverse(classes) for img, yt, yp in zip(file_names, y_true, y_pred): if yt != yp: # and class_count[yp] < n: plt.cla() img = np.asarray(Image.open(join(img_path, img))) ax.imshow(img) # np.transpose(img, (1, 2, 0))) ax.text(5, 10, 'True: {}'.format(classes[yt]), fontdict=FONT) ax.text(5, 25, 'Predicted: {}'.format(classes[yp]), fontdict=FONT) ax.axis('off') plt.savefig(join(out_dir, '{}_{}.png'.format(classes[yp], class_count[yp]))) class_count[yp] += 1