我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.clf()。
def plot_interpolation(orderx,ordery): s = PseudoSpectralDiscretization2D(orderx,XMIN,XMAX, ordery,YMIN,YMAX) Xc,Yc = s.get_x2d() x = np.linspace(XMIN,XMAX,100) y = np.linspace(YMIN,YMAX,100) Xf,Yf = np.meshgrid(x,y,indexing='ij') f_coarse = f(Xc,Yc) f_interpolator = s.to_continuum(f_coarse) f_num = f_interpolator(Xf,Yf) plt.pcolor(Xf,Yf,f_num) cb = plt.colorbar() cb.set_label('interpolated function',fontsize=16) plt.xlabel('x') plt.ylabel('y') for postfix in ['.png','.pdf']: name = 'orthopoly_interpolated_function'+postfix if USE_FIGS_DIR: name = 'figs/' + name plt.savefig(name, bbox_inches='tight') plt.clf()
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 save_fig(file_name, clear=True): if not os.path.exists(FIGURES_DIR): os.makedirs(FIGURES_DIR) if file_name is not None: plt.savefig(FIGURES_DIR + '/' + file_name + '.png') # save for report # if "--timestamp" in file_name: # dir = FIGURES_DIR + "/final" # if not os.path.exists(dir): # os.makedirs(dir) # # file_name = file_name[:file_name.find("--timestamp")] # plt.savefig(dir + '/' + file_name + '.png', dpi=DPI) if clear: plt.clf()
def flush(): prints = [] for name, vals in _since_last_flush.items(): prints.append("{}\t{}".format(name, np.mean(list(vals.values())))) _since_beginning[name].update(vals) x_vals = np.sort(list(_since_beginning[name].keys())) y_vals = [_since_beginning[name][x] for x in x_vals] plt.clf() plt.plot(x_vals, y_vals) plt.xlabel('iteration') plt.ylabel(name) plt.savefig('generated/'+name.replace(' ', '_')+'.jpg') print("iter {}\t{}".format(_iter[0], "\t".join(prints))) _since_last_flush.clear() with open('log.pkl', 'wb') as f: pickle.dump(dict(_since_beginning), f, 4)
def save_ims(filename, ims, dpi=100, scale=0.5): n, c, h, w = ims.shape rows = int(math.ceil(math.sqrt(n))) cols = int(round(math.sqrt(n))) fig, axes = plt.subplots(rows, cols, figsize=(w*cols/dpi*scale, h*rows/dpi*scale), dpi=dpi) for i, ax in enumerate(axes.flat): if i < n: ax.imshow(ims[i].transpose((1, 2, 0))) ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0.1, hspace=0.1) plt.savefig(filename, dpi=dpi, bbox_inces='tight', transparent=True) plt.clf() plt.close()
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]): plt.clf() plt.axis(axes) plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity for i, txt in enumerate(origData): plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels #add lines for edges for edge in [e for e in ripsComplex if len(e)==2]: #print(edge) pt1,pt2 = [origData[pt] for pt in [n for n in edge]] #plt.gca().add_line(plt.Line2D(pt1,pt2)) line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r') plt.gca().add_line(line) #add triangles for triangle in [t for t in ripsComplex if len(t)==3]: pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]] line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None) plt.gca().add_line(line) plt.show()
def drawComplex(data, ph, axes=[-6, 8, -6, 6]): plt.clf() plt.axis(axes) # axes = [x1, x2, y1, y2] plt.scatter(data[:, 0], data[:, 1]) # plotting just for clarity for i, txt in enumerate(data): plt.annotate(i, (data[i][0] + 0.05, data[i][1])) # add labels # add lines for edges for edge in [e for e in ph.ripsComplex if len(e) == 2]: # print(edge) pt1, pt2 = [data[pt] for pt in [n for n in edge]] # plt.gca().add_line(plt.Line2D(pt1,pt2)) line = plt.Polygon([pt1, pt2], closed=None, fill=None, edgecolor='r') plt.gca().add_line(line) # add triangles for triangle in [t for t in ph.ripsComplex if len(t) == 3]: pt1, pt2, pt3 = [data[pt] for pt in [n for n in triangle]] line = plt.Polygon([pt1, pt2, pt3], closed=False, color="blue", alpha=0.3, fill=True, edgecolor=None) plt.gca().add_line(line) plt.show()
def save_fft(fil,audio_in): samples = len(audio_in) fft_size = 2**int(floor(log(samples)/log(2.0))) freq = fft(audio_in[0:fft_size]) s_data = numpy.zeros(fft_size/2) x_data = numpy.zeros(fft_size/2) peak = 0; for j in xrange(fft_size/2): if (abs(freq[j]) > peak): peak = abs(freq[j]) for j in xrange(fft_size/2): x_data[j] = log(2.0*(j+1.0)/fft_size); if (x_data[j] < -10): x_data[j] = -10 s_data[j] = 10.0*log(abs(freq[j])/peak)/log(10.0) plt.ylim([-50,0]) plt.plot(x_data,s_data) plt.title('fft log power') plt.grid() fields = fil.split('.') plt.savefig(fields[0]+'_fft.png', bbox_inches="tight") plt.clf() plt.close()
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 _plot_old_pred_data(old_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, algorithm_str, minutes_str): actual_bg_array = old_pred_data.result_actual_bg_array actual_bg_time_array = old_pred_data.result_actual_bg_time_array pred_array = old_pred_data.result_pred_array pred_time_array = old_pred_data.result_pred_time_array #Root mean squared error rms = math.sqrt(metrics.mean_squared_error(actual_bg_array, pred_array)) print " Root Mean Squared Error: " + str(rms) print " Mean Absolute Error: " + str(metrics.mean_absolute_error(actual_bg_array, pred_array)) print " R^2 Coefficient of Determination: " + str(metrics.r2_score(actual_bg_array, pred_array)) plot, zone = ClarkeErrorGrid.clarke_error_grid(actual_bg_array, pred_array, id_str + " " + algorithm_str + " " + minutes_str) print " Percent A:{}".format(float(zone[0]) / (zone[0] + zone[1] + zone[2] + zone[3] + zone[4])) print " Percent C, D, E:{}".format(float(zone[2] + zone[3] + zone[4])/ (zone[0] + zone[1] + zone[2] + zone[3] + zone[4])) print " Zones are A:{}, B:{}, C:{}, D:{}, E:{}\n".format(zone[0],zone[1],zone[2],zone[3],zone[4]) if save_clarke_plot: plt.savefig(id_str + algorithm_str.replace(" ", "") + minutes_str + "clarke.png") if show_clarke_plot: plot.show() plt.clf() plt.plot(actual_bg_time_array, actual_bg_array, label="Actual BG", color='black', linestyle='-') plt.plot(pred_time_array, pred_array, label="BG Prediction", color='black', linestyle=':') plt.title(id_str + " " + algorithm_str + " " + minutes_str + " BG Analysis") plt.ylabel("Blood Glucose Level (mg/dl)") plt.xlabel("Time (minutes)") plt.legend(loc='upper left') # SHOW/SAVE PLOT DEPENDING ON THE BOOLEAN PARAMETER if save_pred_plot: plt.savefig(id_str + algorithm_str.replace(" ","") + minutes_str + "plot.png") if show_pred_plot: plt.show() #Function to analyze the old OpenAPS data
def plot_heatmaps(data, mis, column_label, cont, topk=30, prefix=''): cmap = sns.cubehelix_palette(as_cmap=True, light=.9) m, nv = mis.shape for j in range(m): inds = np.argsort(- mis[j, :])[:topk] if len(inds) >= 2: plt.clf() order = np.argsort(cont[:,j]) subdata = data[:, inds][order].T subdata -= np.nanmean(subdata, axis=1, keepdims=True) subdata /= np.nanstd(subdata, axis=1, keepdims=True) columns = [column_label[i] for i in inds] sns.heatmap(subdata, vmin=-3, vmax=3, cmap=cmap, yticklabels=columns, xticklabels=False, mask=np.isnan(subdata)) filename = '{}/heatmaps/group_num={}.png'.format(prefix, j) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) plt.title("Latent factor {}".format(j)) plt.yticks(rotation=0) plt.savefig(filename, bbox_inches='tight') plt.close('all') #plot_rels(data[:, inds], map(lambda q: column_label[q], inds), colors=cont[:, j], # outfile=prefix + '/relationships/group_num=' + str(j), latent=labels[:, j], alpha=0.1)
def display_pr_curve(precision, recall): # following examples from sklearn # TODO: f1 operating point import pylab as plt # Plot Precision-Recall curve plt.clf() plt.plot(recall, precision, label='Precision-Recall curve') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Precision-Recall example: Max f1={0:0.2f}'.format(max_f1)) plt.legend(loc="lower left") plt.show()
def render(self, show=True, new_figure=True): """Render the quantized image :param bool show: if the quantized image is also to be shown and not only drawn. :param bool new_figure: if a new figure is to be used. """ if new_figure: plt.figure() plt.clf() plt.title('{method} ({n_colors})'.format( method=self._method, n_colors=self._n_colors)) plt.imshow(self._quantized_raster / 255.0) plt.draw() if show: plt.show()
def sample(self, filename, save_samples): gan = self.gan generator = gan.generator.sample sess = gan.session config = gan.config x_v, z_v = sess.run([gan.inputs.x, gan.encoder.z]) sample = sess.run(generator, {gan.inputs.x: x_v, gan.encoder.z: z_v}) plt.clf() fig = plt.figure(figsize=(3,3)) plt.scatter(*zip(*x_v), c='b') plt.scatter(*zip(*sample), c='r') plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.ylabel("z") fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) #plt.savefig(filename) self.plot(data, filename, save_samples) return [{'image': filename, 'label': '2d'}]
def view(realDtb, fakeDtb, discriminator, outDir): plt.clf() axes = plt.gca() axes.set_xlim([-1,10]) axes.set_ylim([0,0.6]) axes.set_autoscale_on(False) plt.axhline(y = discriminator) plt.plot() real_mean = np.mean(realDtb) real_std = np.std(realDtb) real_pdf = norm.pdf(realDtb, real_mean, real_std) plt.plot(realDtb, real_pdf) fake_mean = np.mean(fakeDtb) fake_std = np.std(fakeDtb) fake_pdf = norm.pdf(fakeDtb, fake_mean, fake_std) plt.plot(fakeDtb, fake_pdf) plt.pause(0.00001)
def cellplot(fs, csf): """ Plots PSF kernels -------------------------------------------------------------------------- Usage: Call: cellplot(fs, csf) Input: fs PSF kernels, i.e. 3d array with kernels indexed by 0th index csf size of kernels in x and y direction Output: Shows stack of PSF kernels arranged according to csf -------------------------------------------------------------------------- Copyright (C) 2011 Michael Hirsch """ mp.clf() for i in range(np.prod(csf)): mp.subplot(csf[0],csf[1],i+1) mp.imshow(fs[i]) mp.axis('off') mp.draw()
def myplot(self): # Plot the results plt.clf() burn=1000 x=np.arange(self.eargs['dsize'])+1 stats=[[],[]] for i,y in enumerate(self.data['y']): stats[0].append(np.mean(y)) stats[1].append(self.eargs['sigma']/np.sqrt(y.size)) plt.errorbar(x,stats[0],yerr=stats[1],fmt='.b',lw=3,ms=12,alpha=0.8) plt.errorbar(x,self.mu['alpha'],yerr=self.sigma['alpha'],fmt='.g',lw=3,ms=12,alpha=0.8) temp1=np.mean(self.chain['mu'][burn:]) plt.plot([0,self.eargs['dsize']+1],[temp1,temp1],'k--') plt.xlim([0,self.eargs['dsize']+1]) plt.ylabel(r'$\alpha_j$') plt.xlabel(r'Group $j$')
def plotImage(dta, saveFigName): plt.clf() dx, dy = 1, 1 # generate 2 2d grids for the x & y bounds with np.errstate(invalid='ignore'): y, x = np.mgrid[ slice(0, len(dta) , dx), slice(0, len(dta[0]), dy) ] z = dta z_min, z_max = -np.abs(z).max(), np.abs(z).max() #try: c = plt.pcolormesh(x, y, z, cmap='hsv', vmin=z_min, vmax=z_max) #except ??? as err: # data not regular? # c = plt.pcolor(x, y, z, cmap='hsv', vmin=z_min, vmax=z_max) d = plt.colorbar(c, orientation='vertical') lx = plt.xlabel("index") ly = plt.ylabel("season length") plt.savefig(str(saveFigName))
def plotACFAndPACF(dta, saveFigName=None): fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(211) # squeeze = Remove single-dimensional entries from the shape of an array. # Plots lags on the horizontal and the correlations on vertical axis ax1.set_ylabel('correlation') ax1.set_xlabel('lag') fig = sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40, ax=ax1) # partial act # Plots lags on the horizontal and the correlations on vertical axis ax2 = fig.add_subplot(212) ax1.set_ylabel('correlation') ax1.set_xlabel('lag') fig = sm.graphics.tsa.plot_pacf(dta, lags=40, ax=ax2) if (saveFigName==None): plt.show() else: plt.savefig(config.plot_dir+str(saveFigName), bbox_inches='tight') plt.clf()
def generate_plot(plot_dir, iteration, data_in, output_g, output_d, train_data, args): data_in = data_in.squeeze() generated = output_g['generated'] plt.plot(data_in[0], data_in[1], 'gx') plt.plot(generated[0], generated[1], 'r.') plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.gca().set_aspect('equal', adjustable='box') plt.axis('off') title = 'Iteration {} \n Gen. Cost {:.2E} Disc. Cost {:.2E}'.format( iteration, float(output_g['batch_cost']), float(output_d['batch_cost'])) plt.title(title) plt.savefig(plot_dir + '/' + str(iteration) + 'Generated.png') plt.clf() # plot and save loss and gradients for key in train_data.keys(): data = np.array(train_data[key]).T plt.plot(data[0], data[1]) plt.title(key + ' for ' + args.loss_type) plt.xlabel('Iterations') plt.ylabel(key) plt.savefig(plot_dir + '/' + key + '.png') plt.clf()
def plot_generated(gen_series, gt_series, predict_seq): """ Plots the generated time series over the ground truth series """ plt.clf() fig, ax = plt.subplots(figsize=(20, 10)) ax.plot(range(gen_series.shape[0]), gen_series[:, 0], linestyle=':', marker='s', label='generated_x') ax.plot(range(gen_series.shape[0]), gen_series[:, 1], linestyle=':', marker='o', label='generated_y') ax.plot(range(gt_series.shape[0]), gt_series[:, 0], linestyle=':', marker='d', label='gt_x') ax.plot(range(gt_series.shape[0]), gt_series[:, 1], linestyle=':', marker='D', label='gt_y') ax.legend() ax.grid() title = 'Lissajous Curve Generated Series and Ground Truth\n' \ 'Predict Sequence:%s' % predict_seq ax.set_title(title) fig.savefig('GeneratedCurve_Time_PredictSeq_%s.png' % predict_seq, dpi=128)
def fit_peak(x, y, display=False): ''' Fit a Gaussian (with linear trend) Parameters ---------- x : array_like x values y : array_like y values display : bool Display the result of the fit Returns ------- par Fit parameters: Gaussian amplitude, Gaussian mean, Gaussian stddev, line slope, line intercept ''' # fit: Gaussian + constant g_init = models.Gaussian1D(amplitude=y.max(), mean=x[np.argmax(y)]) + models.Linear1D(slope=0, intercept=0) fitter = fitting.LevMarLSQFitter() fit = fitter(g_init, x, y) if display: plt.clf() plt.plot(x, y, color='k') plt.plot(x, fit(x), color='r') plt.tight_layout() return fit.parameters
def visualize(X, Y, classes, samples_per_class=10): nb_classes = len(classes) for y, cls in enumerate(classes): idxs = np.flatnonzero(Y == y) idxs = np.random.choice(idxs, samples_per_class, replace=False) for i, idx in enumerate(idxs): plt_idx = i * nb_classes + y + 1 plt.subplot(samples_per_class, nb_classes, plt_idx) plt.imshow(X[idx], cmap='gray') plt.axis('off') if i == 0: plt.title(cls) #plt.show() plt.savefig('img/data.png') plt.clf()
def plot_weight_histogram(model, outfile, lower=-0.25, upper=0.25): n = len(model.params) plt.clf() for (i, theano_shared_params) in enumerate(model.params): weights = theano_shared_params.get_value() values = weights.flatten() plt.subplot(n,1,i+1) frame = plt.gca() frame.axes.get_yaxis().set_ticks([]) if i != n-1: ## only keep bottom one frame.axes.get_xaxis().set_ticks([]) plt.hist(values, 100) plt.xlim(lower, upper) print(' param no. %s'%(i)) print(get_stats(theano_shared_params)) plt.savefig(outfile) print('Made plot %s'%(outfile))
def show_image(im: Image, fig=None, title: str = '', pol=0, chan=0, cm='rainbow'): """ Show an Image with coordinates using matplotlib :param im: :param fig: :param title: :return: """ import matplotlib.pyplot as plt assert isinstance(im, Image) if not fig: fig = plt.figure() plt.clf() fig.add_subplot(111, projection=im.wcs.sub(['longitude', 'latitude'])) if len(im.data.shape) == 4: plt.imshow(numpy.real(im.data[chan, pol, :, :]), origin='lower', cmap=cm) elif len(im.data.shape) == 2: plt.imshow(numpy.real(im.data[:, :]), origin='lower', cmap=cm) plt.xlabel('RA---SIN') plt.ylabel('DEC--SIN') plt.title(title) plt.colorbar() return fig
def plot_conf_mat(densmap_name): fig = plt.figure(figsize = (20,20)) plt.clf() ax = fig.add_subplot(111) #ax.set_aspect(1) densmap = np.fromfile(densmap_name, np.float32) densmap = densmap.reshape(227, 227) densmap *= 100 densmap[densmap > 1] = 1 res = ax.imshow(densmap, cmap = plt.cm.jet, interpolation = 'nearest') plt.savefig('density.jpg') img = cv2.imread("density.jpg") img = cv2.resize(img, (227,227)) cv2.imshow("i", img)# cv2.waitKey(0) #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 create_chart(self, top, others): plt.clf() sizes = [x[1] for x in top] labels = ["{} {:g}%".format(x[0], x[1]) for x in top] if len(top) >= 10: sizes = sizes + [others] labels = labels + ["Others {:g}%".format(others)] title = plt.title('User activity in the last 5000 messages') title.set_va("top") title.set_ha("left") plt.gca().axis("equal") colors = ['r', 'darkorange', 'gold', 'y', 'olivedrab', 'green', 'darkcyan', 'mediumblue', 'darkblue', 'blueviolet', 'indigo'] pie = plt.pie(sizes, colors=colors, startangle=0) plt.legend(pie[0], labels, bbox_to_anchor=(0.7, 0.5), loc="center", fontsize=10, bbox_transform=plt.gcf().transFigure) plt.subplots_adjust(left=0.0, bottom=0.1, right=0.45) image_object = BytesIO() plt.savefig(image_object, format='PNG') image_object.seek(0) return image_object
def plotEvolutionMonitoring(self, estimator = None): if estimator is None: for e in self.homogeneity_estimators + self.adjusted_estimators: self.plotEvolutionMonitoring(estimator = e) else: iterations = range(self.monitoring.iteration_number) plt.clf() max_value = 1 clusterings = self.annotations.getClusteringsEvaluations() for l in clusterings.keys(): color = colors_tools.getLabelColor(l) label = l + '_' + estimator plt.plot(iterations, self.data.loc[:][label], label = l.title() + ' Clustering', color = color, linewidth = 4, marker = 'o') plt.ylim(0, max_value) plt.xlabel('Iteration') plt.ylabel(estimator) lgd = plt.legend(bbox_to_anchor = (0., 1.02, 1., .102), loc = 3, ncol = 2, mode = 'expand', borderaxespad = 0., fontsize = 'large') filename = self.output_directory filename += estimator + '_monitoring.png' plt.savefig(filename, bbox_extra_artists=(lgd,), bbox_inches='tight') plt.clf()
def save_peak(sample, energy): """ Plot peak using Spectrum_Peak_Visualization and save into a PNG file. """ cwd = os.getcwd() sample_name = os.path.splitext(sample.filename)[0] sample_folder = os.path.join(cwd, sample_name) # if folder exists, skip next step. Otherwise, create folder for PNGs if not os.path.exists(sample_folder): try: os.makedirs(sample_folder) except OSError: pass label = sample_name + '_' + str(energy) + '_peak' fwhm = 0.05 * (energy)**0.5 energy_range = [(energy - 11 * fwhm), (energy + 11 * fwhm)] # generate plot PNG using plotter plotter.gamma_plotter( sample, energy_range=energy_range, use='peaks', title_text=label) PNG_name = label + '.png' # move PNGs to newly created folder plt.savefig(os.path.join(sample_folder, PNG_name)) plt.clf()
def exportPlot(self): # Combine to one self.plot_output_file, filetype = QtWidgets.QFileDialog.getSaveFileName(self, "Export Plots To...", "", "PDF(*.pdf)") if filetype == "PDF(*.pdf)": pdf = matplotlib.backends.backend_pdf.PdfPages(self.plot_output_file) for key in list(self.plot_file.keys()): for i in range(1, len(self.plot_file[key])): fig = plt.figure() img = mpimg.imread(self.plot_file[key][i]) plt.imshow(img) plt.axis('off') pdf.savefig(fig) plt.clf() plt.close() pdf.close() sys.stdout.write("Output plot files to %s"%(self.plot_output_file)) self.exportPlot_flag = 1
def plot(data, dec, filename="data.png"): idx = dec[ np.where(dec != 51)[0] ] convex = data[idx, :] x = data[1:, 0] y = data[1:, 1] convex_x = convex[1:, 0] convex_y = convex[1:, 1] plt.scatter(x, y) plt.plot(convex_x, convex_y, color="orange") plt.xlim(0.0, 1.0) plt.ylim(0.0, 1.0) plt.savefig(filename) plt.clf() plt.close()
def corner_plot(self): """ Make triangle plot for visuaizaliton of the multi-dimensional posterior """ plt.clf() plt.figure(1) if self.n_params == 3: self.samples[:,2] = self.samples[:,2] * 1e5 fig = corner.corner(self.samples,bins=30,quantiles=(0.16,0.5, 0.84), labels=[r'$\log N\,[\rm cm^{-3}]$',r'$b\,[\rm km s^{-1}]$',r'$z \times 1e5$'], show_titles=True,title_kwargs={"fontsize": 16}) else: self.samples[:,2] = self.samples[:,2] * 1e5 fig = corner.corner(self.samples,bins=30,quantiles=(0.16,0.5, 0.84), show_titles=True,title_kwargs={"fontsize": 16}) output_name = self.config_param.processed_product_path + '/corner_' + self.config_param.chain_short_fname + '.png' plt.savefig(output_name,bbox_inches='tight') plt.clf() print('Written %s' % output_name)
def plot_gr_indicator(self): """ Make plot for the evolution of GR indicator as a function of steps """ gr_fname = self.config_param.chain_fname + '_GR.dat' data = np.loadtxt(gr_fname,unpack=True) steps = data[0]; grs = data[1:] plt.figure(1,figsize=(6,6)) for i in xrange(len(grs)): plt.plot(steps,grs[i],label=str(i)) plt.legend(loc='best') plt.xscale('log') plt.xlabel(r'$N(\rm{steps})$') plt.ylabel(r'$R_{\rm GR}$') output_name = self.config_param.processed_product_path + '/GR_' + self.config_param.chain_short_fname + '.pdf' plt.savefig(output_name,bbox_inches='tight',dpi=100) plt.clf() print('Written %s' % output_name)
def plot_loss(train_losses, dev_losses, steps, save_path): """Save history of training & dev loss as figure. Args: train_losses (list): train losses dev_losses (list): dev losses steps (list): steps """ # Save as csv file loss_graph = np.column_stack((steps, train_losses, dev_losses)) if os.path.isfile(os.path.join(save_path, "ler.csv")): os.remove(os.path.join(save_path, "ler.csv")) np.savetxt(os.path.join(save_path, "loss.csv"), loss_graph, delimiter=",") # TODO: error check for inf loss # Plot & save as png file plt.clf() plt.plot(steps, train_losses, blue, label="Train") plt.plot(steps, dev_losses, orange, label="Dev") plt.xlabel('step', fontsize=12) plt.ylabel('loss', fontsize=12) plt.legend(loc="upper right", fontsize=12) if os.path.isfile(os.path.join(save_path, "loss.png")): os.remove(os.path.join(save_path, "loss.png")) plt.savefig(os.path.join(save_path, "loss.png"), dvi=500)
def _render(self, mode = "human", close = False): if close: return import matplotlib.pyplot as plt if self.tick == 0: plt.ion() G = self.G attrs = nx.get_node_attributes(G, "ndd") values = ["red" if attrs[v] else "blue" for v in G.nodes()] plt.clf() nx.draw(G, pos = nx.circular_layout(G), node_color = values) plt.pause(0.01) return []
def _render(self, mode='human', close=False): if self.inited == False: return if self.render_on == 0: # self.fig = plt.figure(figsize=(10, 4)) self.fig = plt.figure(figsize=(12, 6)) self.render_on = 1 plt.ion() plt.clf() self._plot_trades() plt.suptitle("Code: " + self.src.symbol + ' ' + \ "Round:" + str(self.reset_count) + "-" + \ "Step:" + str(self.src.idx - self.src.orgin_idx) + " (" + \ "from:" + self.src.reset_start_day + " " + \ "to:" + self.src.reset_end_day + ")") plt.pause(0.001) return self.fig
def plot(self, filename): r"""Save an image file of the transfer function. This function loads up matplotlib, plots the transfer function and saves. Parameters ---------- filename : string The file to save out the plot as. Examples -------- >>> tf = TransferFunction( (-10.0, -5.0) ) >>> tf.add_gaussian(-9.0, 0.01, 1.0) >>> tf.plot("sample.png") """ import matplotlib matplotlib.use("Agg") import pylab pylab.clf() pylab.plot(self.x, self.y, 'xk-') pylab.xlim(*self.x_bounds) pylab.ylim(0.0, 1.0) pylab.savefig(filename)
def show(self): r"""Display an image of the transfer function This function loads up matplotlib and displays the current transfer function. Parameters ---------- Examples -------- >>> tf = TransferFunction( (-10.0, -5.0) ) >>> tf.add_gaussian(-9.0, 0.01, 1.0) >>> tf.show() """ import pylab pylab.clf() pylab.plot(self.x, self.y, 'xk-') pylab.xlim(*self.x_bounds) pylab.ylim(0.0, 1.0) pylab.draw()
def visualize_polar(state): plt.clf() sonar = state[0][-1:] readings = state[0][:-1] r = [] t = [] for i, s in enumerate(readings): r.append(math.radians(i * 6)) t.append(s) ax = plt.subplot(111, polar=True) ax.set_theta_zero_location('W') ax.set_theta_direction(-1) ax.set_ylim(bottom=0, top=105) plt.plot(r, t) plt.scatter(math.radians(90), sonar, s=50) plt.draw() plt.pause(0.1)
def plotD(initD, latestD, workDir): def p(D, fname): plt.clf() lim = max(np.abs(np.min(D)), np.abs(np.max(D))) clim = (-lim, lim) plt.imshow(D, cmap='bwr', interpolation='nearest', clim=clim) plt.colorbar() plt.savefig(os.path.join(workDir, fname)) p(initD, 'initD.png') p(latestD, 'latestD.png') latestDs = latestD**6 latestDs = latestDs/np.sum(latestDs, axis=1)[:,None] I = np.argsort(latestDs.dot(np.arange(latestDs.shape[1]))) latestDs = latestD[I] initDs = initD[I] p(initDs, 'initD_sorted.png') p(latestDs, 'latestD_sorted.png') # Dcombined = np.concatenate((initDs, np.zeros((initD.shape[0], 10)), latestDs), axis=1) # p(Dcombined, 'Dcombined.png')
def test_plot(self): fig = plt.figure() ax = fig.gca(projection='3d') gimbal = GimbalPlot() gimbal.plot(ax) debug = False if debug: axis_equal_3dplot(ax) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") plt.show() plt.clf()
def flush(): prints = [] for name, vals in _since_last_flush.items(): prints.append("{}\t{}".format(name, np.mean(vals.values()))) _since_beginning[name].update(vals) x_vals = np.sort(_since_beginning[name].keys()) y_vals = [_since_beginning[name][x] for x in x_vals] plt.clf() plt.plot(x_vals, y_vals) plt.xlabel('iteration') plt.ylabel(name) plt.savefig(name.replace(' ', '_')+'.jpg') print "iter {}\t{}".format(_iter[0], "\t".join(prints)) _since_last_flush.clear() with open('log.pkl', 'wb') as f: pickle.dump(dict(_since_beginning), f, pickle.HIGHEST_PROTOCOL)
def save_heatmap(heatmap, mask): plt.clf() xmin, xmax, ymin, ymax = 0, heatmap.shape[1], heatmap.shape[0], 0 extent = xmin, xmax, ymin, ymax alpha=1.0 if mask is not None: alpha=0.5 xmin, xmax, ymin, ymax = (0, max(heatmap.shape[1], mask.shape[1]), max(heatmap.shape[0], mask.shape[0]), 0) extent = xmin, xmax, ymin, ymax plt.imshow(mask, extent=extent) plt.hold(True) plt.suptitle("Heatmap of sampled tiles.") plt.imshow(heatmap, cmap='gnuplot', interpolation='nearest', extent=extent, alpha=alpha) return plt
def save_histogram_with_otsu(name, histograms, otsu): plt.clf() figure, axarr = plt.subplots(3) figure.tight_layout() for x, otsu_value in zip(range(3), otsu): axarr[x].bar(np.arange(0, histograms[x].size), np.log2(np.where(histograms[x] >= 1, histograms[x], 1)), 1.0) axarr[x].grid(True) axarr[x].set_ylabel("log2") for val in otsu_value: axarr[x].axvline(x=val, color="r") axarr[x].set_xlim(0, histograms[x].size) axarr[0].set_title('Hue') axarr[1].set_title('Saturation') axarr[2].set_title('Value') return plt
def save_thresholds_heatmap(hmap, hist, bins, heatmap_otsu, mini): plt.clf() width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 ax = plt.subplot(1, 2, 1) ax.bar(center, hist, width=width) ax.grid(True) ax.set_xlim(0.0, 1.0) ax.set_title('Values histogram') ax.set_ylabel("Percent of samples (%)") ax.axvline(x=heatmap_otsu, color="r") ax = plt.subplot(2, 2, 2) ax.set_title('Values heatmap') ax.imshow(hmap, cmap='hot', interpolation='nearest') ax = plt.subplot(2, 2, 4) ax.set_title("Original mini") ax.imshow(mini) return plt
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()