我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.savefig()。
def plot_sent_trajectories(sents, decode_plot): font = {'family' : 'normal', 'size' : 14} matplotlib.rc('font', **font) i = 0 l = ["Portuguese","Catalan"] axes = plt.gca() #axes.set_xlim([xmin,xmax]) axes.set_ylim([-1,1]) for sent, enc in zip(sents, decode_plot): if i==2: continue i += 1 #times = np.arange(len(enc)) times = np.linspace(0,1,len(enc)) plt.plot(times, enc, label=l[i-1]) plt.title("Hidden Node Trajectories") plt.xlabel('timestep') plt.ylabel('trajectories') plt.legend(loc='best') plt.savefig("final_tests/cr_por_cat_hidden_cell_trajectories", bbox_inches="tight") plt.close()
def main(): args.input_data_dir = os.path.abspath(args.input_data_dir) if not os.path.exists(args.output_data_dir): os.mkdir(args.output_data_dir) for dir_path, dir_names, file_names in os.walk(args.input_data_dir): if len(file_names) > 0: print(dir_path) rows = int(math.ceil(len(file_names) / 6.0)) print(rows) fig, axes = plt.subplots(4, 12, subplot_kw={'xticks': [], 'yticks': []}) fig.subplots_adjust(hspace=0.01, wspace=0.01) for ax, file_name in zip(axes.flat, file_names): print(file_name) img = imread(dir_path + '/' + file_name) ax.imshow(img) # ax.set_title(os.path.splitext(file_name)[0].replace('.227x227', '')) plt.savefig(args.output_data_dir + dir_path.replace(args.input_data_dir, '') + '.pdf')
def saveHintonPlot(self, matrix, num_tests, max_weight=None, ax=None): """Draw Hinton diagram for visualizing a weight matrix.""" fig,ax = plt.subplots(1,1) if not max_weight: max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2)) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(matrix): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(0.5*w/num_tests)) # Need to scale so that it is between 0 and 0.5 rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.invert_yaxis() plt.savefig(self.figures_path + self.save_prefix + '-Hinton.eps') plt.close()
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 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 view_trigger_snippets_bis(trigger_snippets, elec_index, save=None): fig = pylab.figure() ax = fig.add_subplot(1, 1, 1) for n in xrange(0, trigger_snippets.shape[2]): y = trigger_snippets[:, elec_index, n] x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1) b = 0.5 + 0.5 * numpy.random.rand() ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid') ax.grid(True) ax.set_xlim([numpy.amin(x), numpy.amax(x)]) ax.set_xlabel("time") ax.set_ylabel("amplitude") if save is None: pylab.show() else: pylab.savefig(save) pylab.close(fig) return
def view_loss_curve(losss, title=None, save=None): '''Plot loss curve''' x_min = 1 x_max = len(losss) - 1 fig = pylab.figure() ax = fig.gca() ax.semilogy(range(x_min, x_max + 1), losss[1:], color='blue', linestyle='solid') ax.grid(True, which='both') if title is None: ax.set_title("Loss curve") else: ax.set_title(title) ax.set_xlabel("iteration") ax.set_ylabel("loss") ax.set_xlim([x_min - 1, x_max + 1]) if save is None: pylab.show() else: pylab.savefig(save) pylab.close(fig) return
def after_run(self, _run_context, run_values): fetches_batch = run_values.results for fetches in unbatch_dict(fetches_batch): # Convert to unicode fetches["predicted_tokens"] = np.char.decode( fetches["predicted_tokens"].astype("S"), "utf-8") fetches["features.source_tokens"] = np.char.decode( fetches["features.source_tokens"].astype("S"), "utf-8") if self.params["dump_plots"]: output_path = os.path.join(self.params["output_dir"], "{:05d}.png".format(self._idx)) _create_figure(fetches) plt.savefig(output_path) plt.close() tf.logging.info("Wrote %s", output_path) self._idx += 1 self._attention_scores_accum.append(_get_scores(fetches))
def make_python_fig(self, code: str, exts: Tuple[str, ...]=('pdf', 'svg'), tight_layout=True) -> str: hashsum = hashlib.md5(code.encode('utf8')).hexdigest() prefix = hashsum[:2] path = os.path.join(self.figures_dir, prefix, hashsum) needfigure = False for ext in exts: if not os.path.isfile(os.path.join( path, self.default_figname + "." + ext)): needfigure = True break if needfigure: make_sure_path_exists(path) gl = self.pythonfigure_globals plt.close() exec(code, gl) if tight_layout: plt.tight_layout() for ext in exts: plt.savefig(os.path.join( path, self.default_figname + "." + ext)) return os.path.join(prefix, hashsum)
def conv1(model): n1, n2, x, y, z = model.conv1.W.shape fig = plt.figure() for nn in range(0, n1): ax = fig.add_subplot(4, 5, nn+1, projection='3d') ax.set_xlim(0.0, x) ax.set_ylim(0.0, y) ax.set_zlim(0.0, z) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_zticklabels([]) for xx in range(0, x): for yy in range(0, y): for zz in range(0, z): max = np.max(model.conv1.W.data[nn, :]) min = np.min(model.conv1.W.data[nn, :]) step = (max - min) / 1.0 C = (model.conv1.W.data[nn, 0, xx, yy, zz] - min) / step color = cm.cool(C) C = abs(1.0 - C) ax.plot(np.array([xx]), np.array([yy]), np.array([zz]), "o", color=color, ms=7.0*C, mew=0.1) plt.savefig("result/graph_conv1.png")
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 main(): parser = generate_parser() args = parser.parse_args() infile1 = h5py.File(args.input1, 'r') infile2 = h5py.File(args.input2, 'r') resolutions = numpy.intersect1d(infile1['resolutions'][...], infile2['resolutions'][...]) chroms = numpy.intersect1d(infile2['chromosomes'][...], infile2['chromosomes'][...]) results = {} data1 = load_data(infile1, chroms, resolutions) data2 = load_data(infile2, chroms, resolutions) infile1.close() infile2.close() results = {} results[(args.input1.split('/')[-1].strip('.quasar'), args.input2.split('/')[-1].strip('.quasar'))] = correlate_samples(data1, data2) for resolution in data1.keys(): for chromo in chroms: plt.scatter(data1[resolution][chromo][1].flatten(),data2[resolution][chromo][1].flatten(),alpha=0.1,color='red') plt.show() plt.savefig(args.output+'.res'+str(resolution)+'.chr'+chromo+'.pdf')
def plot_traing_info(x, ylist, path): """ Loads log file and plot x and y values as provided by input. Saves as <path>/train_log.png """ file_name = os.path.join(path, __train_log_file_name) try: with open(file_name, "rb") as f: log = pickle.load(f) except IOError: # first time warnings.warn("There is no {} file here!!!".format(file_name)) return plt.figure() x_vals = log[x] for y in ylist: y_vals = log[y] if len(y_vals) != len(x_vals): warning.warn("One of y's: {} does not have the same length as x:{}".format(y, x)) plt.plot(x_vals, y_vals, label=y) # assert len(y_vals) == len(x_vals), "not the same len" plt.xlabel(x) plt.legend() #plt.show() plt.savefig(file_name[:-3]+'png', bbox_inches='tight') plt.close('all')
def plot_spectra(results): plt.figure(figsize=(10, 4)) plt.imshow( np.concatenate( [np.flipud(results['x'].T), np.flipud(results['xh'].T), np.flipud(results['x_conv'].T)], 0), aspect='auto', cmap='jet', ) plt.colorbar() plt.title('Upper: Real input; Mid: Reconstrution; Lower: Conversion to target.') plt.savefig( os.path.join( args.logdir, '{}.png'.format( os.path.split(str(results['f'], 'utf-8'))[-1] ) ) )
def plot_single_day_traffic(df): y_tj_l1 = df["tj_level1_count"] y_tj_l2 = df["tj_level2_count"] y_tj_l3 = df["tj_level3_count"] y_tj_l4 = df["tj_level4_count"] x_time = df["time"] x_district = df["district"] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(x_time, x_district, y_tj_l1, ) #ax.plot_surface(x_time, x_district, y_tj_l1) print(plt.get_backend()) plt.show() plt.savefig("plot_traffic.png")
def plotGeneratedImages(epoch,example=100,dim=(10,10),figsize=(10,10)): noise = np.random.normal(0,1,size=(example,randomDim)) generatedImage = generator.predict(noise) generatedImage = generatedImage.reshape(example,28,28) plt.figure(figsize=figsize) for i in range(example): plt.subplot(dim[0],dim[1],i+1) plt.imshow(generatedImage[i],interpolation='nearest',cmap='gray') '''drop the x and y axis''' plt.axis('off') plt.tight_layout() if not os.path.exists('generated_image'): os.mkdir('generated_image') plt.savefig('generated_image/wgan_generated_img_epoch_%d.png' % epoch)
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 on_train_end(self, logs={}): self.model.set_weights(self.best_weights) try: self.model.save('copy.model') except Exception: print('could not save model') if self.verbose > 0: print(' {:.1f} min'.format((time.time()-self.start)/60), flush=True) if self.plot: filename ='{}_{}_{}.png'.format(self.counter, self.name, self.model.name) filename = ''.join([x if x not in ',;\\/:><|?*\"' else '_' for x in filename]) try: plt.savefig(os.path.join('.','plots', filename )) except Exception as e:print('can\'t save plots: {}'.format(e)) # try: # self.model.save(os.path.join('.','weights', str(self.counter) + self.model.name)) # except Exception as error: # print("Got an error while saving model: {}".format(error)) # return #%%
def plotValResults(self, save_path=None, label=None): if label is not None: accs = self.training_val_results['acc'][label] aucs = self.training_val_results['auc'][label] else: accs = self.training_val_results['acc'] aucs = self.training_val_results['auc'] plt.figure() plt.plot([i * ACCURACY_LOGGED_EVERY_N_STEPS for i in range(len(accs))], accs) plt.plot([i * ACCURACY_LOGGED_EVERY_N_STEPS for i in range(len(aucs))], aucs) plt.xlabel('Training step') plt.ylabel('Validation accuracy') plt.legend(['Accuracy','AUC']) if save_path is None: plt.show() else: plt.savefig(save_path) plt.close()
def plotValResults(self, save_path=None, label=None): if label: accs = self.training_val_results_per_task['acc'][label] aucs = self.training_val_results_per_task['auc'][label] else: accs = self.training_val_results['acc'] aucs = self.training_val_results['auc'] plt.figure() plt.plot([i * self.accuracy_logged_every_n for i in range(len(accs))], accs) plt.plot([i * self.accuracy_logged_every_n for i in range(len(aucs))], aucs) plt.xlabel('Training step') plt.ylabel('Validation accuracy') plt.legend(['Accuracy','AUC']) if save_path is None: plt.show() else: plt.savefig(save_path)
def plot_with_labels(low_dim_embs, labels, filename='tsne.png'): assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings" plt.figure(figsize=(18, 18)) # in inches x = low_dim_embs[:, 0] y = low_dim_embs[:, 1] plt.scatter(x, y) for i, label in enumerate(labels): x, y = low_dim_embs[i, :] plt.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom') plt.show() # plt.savefig(filename)
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 Energy_Flow(Time_Series): Energy_Flow = {'Energy_Demand':0, 'Lost Load':0, 'Energy PV':0,'Curtailment':0, 'Energy Diesel':0, 'Discharge energy from the Battery':0, 'Charge energy to the Battery':0} for v in Energy_Flow.keys(): if v == 'Energy PV': Energy_Flow[v] = round((Time_Series[v].sum() - Time_Series['Curtailment'].sum()- Time_Series['Charge energy to the Battery'].sum())/1000000, 2) else: Energy_Flow[v] = round((Time_Series[v].sum())/1000000, 2) c = ['From Generator', 'To Battery', 'Demand', 'From PV', 'From Battery', 'Curtailment', 'Lost Load'] plt.figure() plt.bar((1,2,3,4,5,6,7), Energy_Flow.values(), color= 'b', alpha=0.3, align='center') plt.xticks((1.2,2.2,3.2,4.2,5.2,6.2,7.2), c) plt.xlabel('Technology') plt.ylabel('Energy Flow (MWh)') plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='on') plt.xticks(rotation=-30) plt.savefig('Results/Energy_Flow.png', bbox_inches='tight') plt.show() return Energy_Flow
def LDR(Time_Series): columns=['Consume diesel', 'Lost Load', 'Energy PV','Curtailment','Energy Diesel', 'Discharge energy from the Battery', 'Charge energy to the Battery', 'Energy_Demand', 'State_Of_Charge_Battery' ] Sort_Values = Time_Series.sort('Energy_Demand', ascending=False) index_values = [] for i in range(len(Time_Series)): index_values.append((i+1)/float(len(Time_Series))*100) Sort_Values = pd.DataFrame(Sort_Values.values/1000, columns=columns, index=index_values) plt.figure() ax = Sort_Values['Energy_Demand'].plot(style='k-',linewidth=1) fmt = '%.0f%%' # Format you want the ticks, e.g. '40%' xticks = mtick.FormatStrFormatter(fmt) ax.xaxis.set_major_formatter(xticks) ax.set_ylabel('Load (kWh)') ax.set_xlabel('Percentage (%)') plt.savefig('Results/LDR.png', bbox_inches='tight') plt.show()
def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'): words = [(i, vocab[i]) for i in s] model = TSNE(n_components=2, random_state=0) #Note that the following line might use a good chunk of RAM tsne_embedding = model.fit_transform(word_embedding_matrix) words_vectors = tsne_embedding[np.array([item[1] for item in words])] plt.subplots_adjust(bottom = 0.1) plt.scatter( words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral')) for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]): plt.annotate( label, xy=(x, y), xytext=(-20, 20), textcoords='offset points', ha='right', va='bottom', fontsize=20, # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0') ) plt.show() # plt.savefig(save_file)
def plot_info_retrieval(precisions, save_file): # markers = ["|", "D", "8", "v", "^", ">", "h", "H", "s", "*", "p", "d", "<"] markers = ["D", "p", 's', "*", "d", "8", "^", "H", "v", ">", "<", "h", "|"] ticks = zip(*zip(*precisions)[1][0])[0] plt.xticks(range(len(ticks)), ticks) new_x = interpolate.interp1d(ticks, range(len(ticks)))(ticks) i = 0 for model_name, val in precisions: fr, pr = zip(*val) plt.plot(new_x, pr, linestyle='-', alpha=0.7, marker=markers[i], markersize=8, label=model_name) i += 1 # plt.legend(model_name) plt.xlabel('Fraction of Retrieved Documents') plt.ylabel('Precision') legend = plt.legend(loc='upper right', shadow=True) plt.savefig(save_file) plt.show()
def get_graphs_from_logs(): with open("Results/logs.dat", "rb") as file: logs = pickle.load(file) for (hus, ep, bt), log in logs.items(): hus = list(map(lambda _c: str(_c), hus)) title = "hus: {} ep: {} bt: {}".format( "- " + " -> ".join(hus) + " -", ep, bt ) fb_log, acc_log = log["fb_log"], log["acc_log"] xs = np.arange(len(fb_log)) + 1 plt.figure() plt.title(title) plt.plot(xs, fb_log) plt.plot(xs, acc_log, c="g") plt.savefig("Results/img/" + "{}_{}_{}".format( "-".join(hus), ep, bt )) plt.close()
def make_comment_plot(data,p_id): """ ???????? :param datas: :return: """ if data: temps = "".join(data).replace(" ", "").replace("\r\n", "") values = re.findall(r'(\d+)', temps) c_values = [int(value) for value in values] c_keys = re.findall('[\u4e00-\u9fa5]+', temps) print(c_keys) s = pd.Series(c_values, index=c_keys,name='???') s = s[3:6] s_sum = s.sum() s = s.apply(lambda x: x / s_sum) s.plot.pie(autopct='%0.2f%%', fontsize=8, colors=['g', 'y', 'r']) plt.savefig("static/upload/%s_c.png" % p_id,dpi=90) plt.close() return file_hepler.get_image_path("%s_c.png" % p_id) else: return file_hepler.get_image_path("no_good_comments.png")
def make_overview_plot(data,p_id): """ ???? :param datas: :return: """ if data: temps = "".join(data) values = re.findall(r'(\d+)', temps) c_values = [int(value) for value in values] c_keys = re.findall('[\u4e00-\u9fa5]+', temps) s = pd.Series(c_values, index=c_keys) s.plot.bar(figsize=(6, 8), fontsize=8) plt.savefig("static/upload/%s_o.png" % p_id,dpi=90) plt.close() return file_hepler.get_image_path("%s_o.png" % p_id) else: return file_hepler.get_image_path("no_overview.png")
def imagePloter(_feature_data, _im): fig = plt.figure(); fig.add_subplot(1, 2, 1); print("Processing Please Wait..."); im = misc.imread(_im); plt.imshow(im); n = 1; for cluster in _feature_data: points = cluster['points']; im = np.zeros((480, 640), dtype=int) im[points] = cluster['values'] #plt.figure(); #plt.imshow(im, cmap='gray') print("Writing Images..."); fig.add_subplot(1, 2, 2); plt.imshow(im); prefix = re.split('IR_|.pgm', _im)[0]; #print(prefix); postfix = re.split('IR_|.pgm', _im)[1]; #print(postfix); plt.savefig(prefix + postfix + "_Cluster_" + str(n) + ".png"); n = n + 1; print("Done.."); return
def plot_histogram(counter, label, plot=None): import matplotlib.pyplot as plt plt.figure() nums = list(counter.keys()) counts = list(counter.values()) indices = range(len(counts)) bars = plt.bar(indices, counts, align="center") plt.xticks(indices, nums) top = 1.06 * max(counts) plt.ylim(min(counts), top) plt.xlabel("number of %s" % label) plt.ylabel("count") for bar in bars: count = bar.get_height() plt.text(bar.get_x() + bar.get_width() / 2., count, "%.1f%%" % (100.0 * count / sum(counts)), ha="center", va="bottom") if plot: plt.savefig(plot + "histogram_" + label + ".png") else: plt.show()
def print_images(base_output_name, image_formats, dpi, path=None, transparent=False): file_base = opath.splitext(opath.basename(base_output_name))[0] for fmt in image_formats: if path: out_name = path else: out_name = "{}.{}".format(file_base, fmt) try: if fmt == 'png': plt.savefig(out_name, dpi=dpi, transparent=transparent) else: plt.savefig(out_name, format=fmt, transparent=transparent) except PermissionError: # thanks to https://github.com/wdecoster for the suggestion print("""You don't have permission to save pauvre plots to this directory. Try changing the directory and running the script again!""")
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 plot(self, df, database_name, test_name, y_label): means = df.rolling(70).mean() ax = means.plot( title=test_name, alpha=0.8, xlim=(0, means.index.max() * 1.05), ylim=(0, means.max().max() * 1.05), ) ax.set(xlabel='Amount of objects in table', ylabel=y_label) ax.xaxis.set_major_formatter( FuncFormatter(lambda v, pos: prefix_unit(v, '', -3))) if y_label in self.ticks_formatters: ax.yaxis.set_major_formatter(self.ticks_formatters[y_label]) legend = ax.legend( loc='upper center', bbox_to_anchor=(0.5, 0.0), bbox_transform=plt.gcf().transFigure, fancybox=True, shadow=True, ncol=3) plt.savefig( os.path.join(self.results_path, '%s - %s.svg' % (database_name, test_name)), bbox_extra_artists=(legend,), bbox_inches='tight', )
def __plot_canvas(self, show, save): if self.x is None: raise Exception("Please run fit() method first") else: plt.close() plt.plot(self.x.real, self.x.imag, '-', color='blue') plt.xlim((0, self.canvas)) plt.ylim((0, self.canvas)) if show and save: plt.savefig(self.path_to_save) plt.show() elif save: if self.path_to_save is None: raise Exception('Please create Trajectory instance with path_to_save') plt.savefig(self.path_to_save) elif show: plt.show()
def __plot_canvas(self, show, save): if len(self.PSFs) == 0: raise Exception("Please run fit() method first.") else: plt.close() fig, axes = plt.subplots(1, self.PSFnumber, figsize=(10, 10)) for i in range(self.PSFnumber): axes[i].imshow(self.PSFs[i], cmap='gray') if show and save: if self.path_to_save is None: raise Exception('Please create Trajectory instance with path_to_save') plt.savefig(self.path_to_save) plt.show() elif save: if self.path_to_save is None: raise Exception('Please create Trajectory instance with path_to_save') plt.savefig(self.path_to_save) elif show: plt.show()
def boxplot_metrics(df, eval_dir): """ Create summary boxplots of all geometric measures. :param df: :param eval_dir: :return: """ boxplots_file = os.path.join(eval_dir, 'boxplots.eps') fig, axes = plt.subplots(3, 1) fig.set_figheight(14) fig.set_figwidth(7) sns.boxplot(x='struc', y='dice', hue='phase', data=df, palette="PRGn", ax=axes[0]) sns.boxplot(x='struc', y='hd', hue='phase', data=df, palette="PRGn", ax=axes[1]) sns.boxplot(x='struc', y='assd', hue='phase', data=df, palette="PRGn", ax=axes[2]) plt.savefig(boxplots_file) plt.close() return 0
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_joints_step(self, stamp): if self.plots == '': return mean_joints = self.get_mean_joints() std_joints = self.get_std_joints() f = plt.figure(facecolor="white", figsize=(16, 12)) ax = f.add_subplot(111) ax.set_title('Mean +- {}std'.format(self.std_factor)) color_id = 0 for joint_id, joint_mean in enumerate(mean_joints): ax.plot(self.x, joint_mean, label='Joint {}'.format(joint_id), color=self.colors[color_id], linestyle='dashed') plt.fill_between(self.x, joint_mean - self.std_factor*std_joints[joint_id], joint_mean + self.std_factor*std_joints[joint_id], alpha=0.1, color=self.colors[color_id]) color_id = (color_id + 1) % len(self.colors) plt.legend(loc='upper left') self._mk_dirs() filename = '_'.join(['joints', stamp]) plt.savefig(join(self.plots, filename) + '.svg', dpi=100, transparent=False) plt.close('all')
def plot_demos(self): if self.plots == '': return yt = self.Y.transpose(2, 0, 1) for joint_id, joint in enumerate(yt): f = plt.figure(facecolor="white", figsize=(16, 12)) ax = f.add_subplot(111) ax.set_title('Joint {}'.format(joint_id)) for demo_id, demo in enumerate(joint): ax.plot(self.x, demo, label='Demo {}'.format(demo_id)) plt.legend() # Save or show plots self._mk_dirs() filename = 'demos_of_joint_{}'.format(joint_id) plt.savefig(join(self.plots, filename) + '.svg', dpi=100, transparent=False) plt.close('all')
def plot_convergence(history, prefix='', prefix2=''): plt.figure(figsize=(8, 5)) ax = plt.subplot(111) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.plot(history["TC"], '-', lw=2.5, color=tableau20[0]) x = len(history["TC"]) y = np.max(history["TC"]) plt.text(0.5 * x, 0.8 * y, "TC", fontsize=18, fontweight='bold', color=tableau20[0]) if history.has_key("additivity"): plt.plot(history["additivity"], '-', lw=2.5, color=tableau20[1]) plt.text(0.5 * x, 0.3 * y, "additivity", fontsize=18, fontweight='bold', color=tableau20[1]) plt.ylabel('TC', fontsize=12, fontweight='bold') plt.xlabel('# Iterations', fontsize=12, fontweight='bold') plt.suptitle('Convergence', fontsize=12) filename = '{}/summary/convergence{}.pdf'.format(prefix, prefix2) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) plt.savefig(filename, bbox_inches="tight") plt.close('all') return True
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 get_stock(symbol): last_year_date = datetime.strftime(datetime.now() - relativedelta(years=1), "%Y-%m-%d") date = get_last_trading_date() url = requests.get('https://www.quandl.com/api/v3/datasets/WIKI/{}.json?start_date={}&end_date={}'.format(symbol, last_year_date, date)) json_dataset = url.json() json_data = json_dataset['dataset']['data'] dates = [] closing = [] for day in json_data: dates.append(datetime.strptime(day[0], "%Y-%m-%d")) closing.append(day[4]) plt.plot_date(dates, closing, '-') plt.title(symbol) plt.xlabel('Date') plt.ylable('Stock Price') plt.savefig('foo.png')
def plot_hist(arr, title): ''' Function to plot a histogram of scores for employers INPUT: arr: Array-like, scores title: String, title for plot OUTPUT: Histogram plot (saved in directory) ''' fig = plt.figure(figsize=(6, 4)) ax = fig.add_subplot(111) ax.set_title(title, fontsize=14) ax.set_xlabel('Overall Score', fontsize=10) ax.set_ylabel('Observations', fontsize=10) ax.hist(arr, bins=(len(arr) / 180)) plt.tight_layout() plt.savefig('images/{}.png'.format(title.replace(' ', '_').lower())) return
def heatmap(src_sent, tgt_sent, att_weights, idx): plt.figure(figsize=(8, 6), dpi=80) att_probs = np.stack(att_weights, axis=1) plt.imshow(att_weights, cmap='gray', interpolation='nearest') #src_sent = [ str(s) for s in src_sent] #tgt_sent = [ str(s) for s in tgt_sent] #plt.xticks(range(0, len(tgt_sent)), tgt_sent, rotation='vertical') #plt.yticks(range(0, len(src_sent)), src_sent) plt.xticks(range(0, len(tgt_sent)),"") plt.yticks(range(0, len(src_sent)),"") plt.axis('off') plt.savefig("att_matrix_"+str(idx), bbox_inches='tight') plt.close()
def plot_trajectories(src_sent, src_encoding, idx): # encoding is (time_steps, hidden_dim) #pca = PCA(n_components=1) #pca_result = pca.fit_transform(src_encoding) times = np.arange(src_encoding.shape[0]) plt.plot(times, src_encoding) plt.title(" ".join(src_sent)) plt.xlabel('timestep') plt.ylabel('trajectories') plt.savefig("misc_hidden_cell_trajectories_"+str(idx), bbox_inches="tight") plt.close()
def plot_test_function(orderx,ordery): s = PseudoSpectralDiscretization2D(orderx,XMIN,XMAX, ordery,YMIN,YMAX) X,Y = s.get_x2d() f_ana = f(X,Y) plt.pcolor(X,Y,f_ana) plt.xlabel('x',fontsize=16) plt.ylabel('y',fontsize=16) plt.xlim(XMIN,XMAX) plt.ylim(YMIN,YMAX) cb = plt.colorbar() cb.set_label(label=r'$\cos(x)\sin(2 y)$',fontsize=16) for postfix in ['.png','.pdf']: name = 'test_function'+postfix if USE_FIGS_DIR: name = 'figs/' + name plt.savefig(name, bbox_inches='tight') plt.clf()