def plot_bar_FeOx(): # FeOx df = pd.read_csv('../results/dynamic_results/FeOx_vintage_results_0226.csv',index_col=[0,1]) market_name = ['Household & Furniture','Automotive','Medical','Other Industries','Packaging','Electronics', 'Construction & Building'] amount=[df.loc[mat,'Manufacturing Release']['2010.0']+df.loc[mat,'In Use']['2010.0']+df.loc[mat,'End of Life']['2010.0'] for mat in market_name] width = 0.15 last_num = 0 color=iter(cm.Set1(np.linspace(0,1,7))) for name,num in zip(market_name,amount): c=next(color) if name == 'Construction & Building': plt.bar(0.1,num,width,bottom=last_num,color=c,label=name,yerr=1000,error_kw=dict(ecolor='rosybrown', lw=2, capsize=5, capthick=2)) else: plt.bar(0.1,num,width,bottom=last_num,color=c,label=name) last_num += num plt.bar(0.7,13860,width,color='salmon',label = 'Static Results (aggregated, all uses)') plt.legend(loc='upper left') plt.xlim(0,1) plt.xticks((0.18,0.78), ('Dynamic Model','Static Model')) plt.tick_params(labelsize=14) plt.show()
def plot_integrated_colors(filenames, labels='Z'): if type(filenames) is str: filenames = [filenames] ax = None cols = ['k'] else: fig, ax = plt.subplots() cols = brewer2mpl.get_map('Spectral', 'Diverging', len(filenames)).mpl_colors if labels == 'Z': fmt = '$Z=%.4f$' labels = [fmt % float(l.replace('.dat', '').split('Z')[1]) for l in filenames] else: print 'need to fix labels' labels = [''] * len(filenames) for i, filename in enumerate(filenames): data = rsp.fileIO.readfile(filename) ycol = 'V-K' xcol = 'Age' ax = rg.color_color(data, xcol, ycol, xscale='log', ax=ax, plt_kw={'lw': 2, 'color': cols[i], 'label': labels[i]}) plot_cluster_data(ax) ax.legend(frameon=False, loc=0, numpoints=1) ax.set_xlabel(r'${\rm %s}$' % xcol, fontsize=20) ax.set_ylabel(r'${\rm %s}$' % ycol, fontsize=20) plt.tick_params(labelsize=16) return ax
def plotRocCurves(file_legend): pylab.clf() pylab.figure(1) pylab.xlabel('1 - Specificity', fontsize=12) pylab.ylabel('Sensitivity', fontsize=12) pylab.title("Need for Referral") pylab.grid(True, which='both') pylab.xticks([i/10.0 for i in range(1,11)]) pylab.yticks([i/10.0 for i in range(0,11)]) pylab.tick_params(axis="both", labelsize=15) for file, legend in file_legend: points = open(file,"rb").readlines() x = [float(p.split()[0]) for p in points] y = [float(p.split()[1]) for p in points] dev = [float(p.split()[2]) for p in points] x = [0.0] + x y = [0.0] + y dev = [0.0] + dev auc = np.trapz(y, x) * 100 aucDev = np.trapz(dev, x) * 100 pylab.grid() pylab.errorbar(x, y, yerr = dev, fmt='-') pylab.plot(x, y, '-', linewidth = 1.5, label = legend + u" (AUC = {0:0.1f}% \xb1 {1:0.1f}%)".format(auc,aucDev)) pylab.legend(loc = 4, borderaxespad=0.4, prop={'size':12}) pylab.savefig("referral/referral-curves.pdf", format='pdf')
def plot_spectrograms(bsl,rec,rate,y,ax): ny_nfft=1024 i=7 plt.tick_params(axis='both', labelsize=8) Pxx, freq, bins, im = ax[y,0].specgram(bsl[i],NFFT=ny_nfft,Fs=rate) ax[y,0].set_yticks(np.arange(0, 50, 10)) ax[y,0].set_ylim([0, 40]) if(y==3): ax[y,0].set_xlabel("Time, seconds", fontsize=10) ax[y,0].set_ylabel("Freq, Hz", fontsize=8) ax[y,0].set_title('Subject '+str(y+1)+' Baseline', fontsize=10) for label in (ax[y,0].get_xticklabels() + ax[y,0].get_yticklabels()): label.set_fontname('Arial') label.set_fontsize(8) Pxx, freq, bins, im = ax[y,1].specgram(rec[i],NFFT=ny_nfft,Fs=rate) ax[y,0].set_yticks(np.arange(0, 50, 10)) ax[y,1].set_ylim([0, 40]) #ax[i,1].set_xlim([0, 10000]) #13000]) if(y==3): ax[y,1].set_xlabel("Time, seconds", fontsize=10) #ax[i,1].set_ylabel("Freq, Hz") ax[y,1].set_title('Subject '+str(y+1)+' Recovery', fontsize=10) for label in (ax[y,0].get_xticklabels() + ax[y,0].get_yticklabels()): label.set_fontname('Arial') label.set_fontsize(8) return
def showStaticImage(request, che_str): import matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt plt.style.use('ggplot') # change type depending on what's in che_string if 'R' in che_str: RR = RTG_Read_Rate elif 'T' in che_str: RR = FEL_Read_Rate # create seperate lists for the dates and the read rates fel_list = che_str.split('+') for fel in fel_list: dates = [] # List for storing dates (x axis) results = [] # List for storing dictionaries for read rates for i in RR.objects.filter(che_id=fel).order_by('date'): dates.append(i.date) results.append(i.read_rate) # Configure the plots for each iteration plt.plot(dates, results, '-o', linewidth=1, label=fel) plt.xticks(rotation=35) plt.tick_params(axis='both', labelsize=8) plt.ylim(0, 1.0) plt.legend(loc='lower left', fontsize='8') response = HttpResponse(content_type='image/png') plt.savefig(response, format='png', dpi=96*1.5) plt.close() return response
def gen_plot(processes,filename): fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(111) c = Counter(processes).items() c.sort(key=itemgetter(1)) c.reverse() #c=c[1:] #c=c[:len(c)/2] labels, values = zip(*c) ll=[] for i in labels: if not (i[0] == '['): ll.append(i.split('/')[-1]) else: ll.append(i) print labels print "------" print ll indexes = np.arange(len(labels)) width = 0.5 ax.bar(indexes, values, width) plt.xticks(indexes+width*0.5 , ll, rotation=90) plt.tick_params(axis='both', which='major', labelsize=10) plt.savefig(filename+'.pdf')
def corr(data,labels,**kwargs): data=np.transpose(data) corrs=np.corrcoef(data) labelsDict=dict((i,labels[i]) for i in range(len(labels))) if 'makeGraph' in kwargs.keys(): if kwargs['makeGraph']==True: fig,ax=plt.subplots() # plt.pcolor(corrs) plt.pcolor(corrs>=kwargs['Tresh']) plt.xticks([i for i in range(44)],rotation=45) ax.set_xticklabels(labels) ax.set_yticklabels(labels) plt.tick_params(axis='both', which='both', labelsize=7) # plt.imshow(corrs>=kwargs['Tresh'],interpolation=None) # plt.colorbar() plt.show() if 'undGraph' in kwargs: plt.figure() if kwargs['undGraph']==True: gcorrs=np.copy(corrs) if 'Tresh' in kwargs: idx=np.where(corrs<=kwargs['Tresh']) gcorrs[idx]=0 gcorrs=gcorrs-np.identity(gcorrs.shape[0]) G=nx.from_numpy_matrix(np.triu(gcorrs)) for node in nx.nodes(G): edges=np.sum([ 1 for i in nx.all_neighbors(G, node)]) if edges==0: G.remove_node(node) labelsDict.pop(node) G=nx.relabel_nodes(G,labelsDict) pos=nx.spring_layout(G,iterations=200) # pos=nx.shell_layout(G) nx.draw_networkx(G,pos,font_size=9) # nx.draw_spring(G) # nx.draw(G,pos,font_size=9) plt.show() if 'ret' in kwargs.keys(): if kwargs['ret']==True: corrs2=np.triu(corrs-np.diagflat(np.diag(corrs))) i,j=np.where(np.abs(corrs2)>=kwargs['Tresh']) # print corrs2[i,j] # print i # print j feats=set(list(i)+list(j)) # print feats return feats
def plot(a,fileig,Q,point_names,ef=0,fildos=None,ymin=None,ymax=None ,pdos_pref=None,atoms=None,pdos_max=None): """docstring for plot""" fig = plt.figure(0,(12, 8)) assert len(Q) == len(point_names), "Length of Q and point_names should be the same!" if fildos != None: ax = plt.axes([.06, .05, .7, .85]) ef,e,dos = dos_reader(fildos) e -= ef elif pdos_pref: ax = plt.axes([.06, .05, .7, .85]) else: ax = fig.add_subplot(111) eig,kpts = eig_reader(fileig) eig -= ef q = kline(kpts,a) for i in xrange(eig.shape[1]): plt.plot(q,eig[:,i],'k-',lw=1) plt.xticks(q[Q], point_names) plt.tick_params(axis='x', labeltop='on',labelsize=15,labelbottom='off') plt.yticks(fontsize=15) plt.xlim(q[0], q[-1]) plt.plot(q,[0]*len(q),'r--') plt.xlabel("Reduced wave number", fontsize=18) plt.ylabel("Electron Energy (eV)", fontsize=18) plt.grid('on') plt.ylim(ymin,ymax) ymin,ymax = plt.ylim() # add an extra ef on the right of the axis.... so troublesome # ax1 = plt.axes([.11, .05, .64, .85],frameon=False) ax1 = plt.axes(ax.get_position(),frameon=False) ax1.yaxis.tick_right() # plt.tick_params(axis='y', labelleft='on',labelright='on',labelsize=15) ax1.xaxis.set_ticklabels([]) ax1.xaxis.set_ticks_position('none') plt.yticks([0],['$\epsilon_{\mathrm{F}}$'],fontsize=15) plt.ylim(ymin,ymax) if fildos: plt.axes([.79, .05, 0.20, .85]) plt.plot(dos,e,'k-',lw=1) plt.ylim(ymin,ymax) plt.xticks([],[]) plt.yticks([],[]) plt.xlabel("DOS",fontsize=18) if pdos_pref: ax2 = plt.axes([.79, .05, 0.20, .85]) plot_pdos(pdos_pref,atoms,ax=ax2) ax2.set_xticks([],[]) ax2.set_yticks([],[]) ax2.set_ylim(ymin,ymax) ax2.set_xlim(0,pdos_max) plt.show() plt.close()
def plot_density(self, vector, coords, max_el=1.0, min_el=0.0, **kwrds): maxel = max_el*np.max(vector) minel = min_el*np.max(vector) print maxel, minel xmin = 0.0 xmax = 0.0 ymin = 0.0 ymax = 0.0 for i in xrange(len(vector)): if maxel != minel: msize = vector[i] * 180. / np.sqrt(np.sqrt(len(vector))) / (maxel-minel) #R = 1/(maxel) * (density1d[i].real) #G = 1/(maxel) * (maxel - density1d[i].real) if vector[i] >= maxel: R = 1 G = 0 elif vector[i] <= minel: G = 1 R = 0 else: R = 0.999 / (maxel - minel) * (vector[i].real - minel) G = 0.999 / (maxel - minel) * (maxel - vector[i].real) B = 0.0 else: msize = 0.0 R = 0.0 G = 0.0 B = 0.0 plt.plot(coords[i][0], coords[i][1], 'o', mfc='k', ms=2) plt.plot(coords[i][0], coords[i][1], 'o', mfc=(R,G,B), ms=msize, **kwrds) if coords[i][0] < xmin: xmin = coords[i][0] elif coords[i][0] > xmax: xmax = coords[i][0] elif coords[i][1] < ymin: ymin = coords[i][0] elif coords[i][1] > ymax: ymax = coords[i][1] dx = (xmax-xmin) / 10. dy = (ymax-ymin) / 10. plt.xlim(xmin - 0.5*dx, xmax + 0.5*dx) plt.ylim(ymin - 0.5*dy, ymax + 0.5*dy) plt.xlabel(r'$x$', fontsize = 26) plt.ylabel(r'$y$', fontsize = 26) plt.tick_params(labelsize=22) #plt.axes().set_aspect('equal') return None
def plot_autocorrs(self, axis=0, n_rows=4, n_cols=8): """ Plot autocorrelations for all antennas """ self.current_plot = 'multi' self.ax_zoomed = False bls = self.uv.d_uv_data['BASELINE'] # Extract the relevant baselines using a truth array # bls = bls.tolist() bl_ids = set([256*i + i for i in range(1, n_rows * n_cols + 1)]) bl_truths = np.array([(b in bl_ids) for b in bls]) #print self.uv.d_uv_data['DATA'].shape #x_data = self.d_uv_data['DATA'][bl_truths,0,0,:,0,axis] # Baselines, freq and stokes #x_cplx = x_data[:,:,0] + 1j * x_data[:,:,1] x_cplx = self.stokes[axis][bl_truths] # Plot the figure #print self.uv.n_ant fig = self.sp_fig figtitle = '%s %s: %s -- %s'%(self.uv.telescope, self.uv.instrument, self.uv.source, self.uv.date_obs) for i in range(n_rows): for j in range(n_cols): ax = fig.add_subplot(n_rows, n_cols, i*n_cols + j +1) ax.set_title(self.uv.d_array_geometry['ANNAME'][i*n_cols + j], fontsize=10) #ax.set_title("%s %s"%(i, j)) x = x_cplx[i*n_cols+j::self.uv.n_ant] if self.scale_select.currentIndex() == 0 or self.scale_select.currentIndex() == 1: if x.shape[0] == self.uv.n_ant: self.plot_spectrum(ax, x, label_axes=False) else: self.plot_spectrum(ax, x, stat='max', label_axes=False) self.plot_spectrum(ax, x, stat='med', label_axes=False) self.plot_spectrum(ax, x, stat='min', label_axes=False) else: self.plot_spectrum(ax, x, label_axes=False) self.updateFreqAxis(ax) if i == n_rows-1: ax.set_xlabel('Freq') if j == 0: ax.set_ylabel('Amplitude') plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.tick_params(axis='both', which='major', labelsize=10) plt.tick_params(axis='both', which='minor', labelsize=8) plt.xticks(rotation=30) plt.subplots_adjust(left=0.05, right=0.98, top=0.95, bottom=0.1, wspace=0.3, hspace=0.45) return fig, ax
def plot_matrix(data): plt.tick_params( axis='both', which='both', labelleft='off', bottom='off', top='off', labelbottom='off', left='off', right='off') plt.imshow( data, interpolation='nearest', cmap=get_matrix_cmap(), vmin=0, vmax=3) plt.colorbar(ticks=range(np.max(data)+1), extend='min')
def violin_plot(ax, values_list, measure_name, group_names, fontsize, color='blue', ttest=False): ''' This is a little wrapper around the statsmodels violinplot code so that it looks nice :) ''' # IMPORTS import matplotlib.pylab as plt import statsmodels.api as sm import numpy as np # Make your violin plot from the values_list # Don't show the box plot because it looks a mess to be honest # we're going to overlay a boxplot on top afterwards plt.sca(ax) # Adjust the font size font = { 'size' : fontsize} plt.rc('font', **font) max_value = np.max(np.concatenate(values_list)) min_value = np.min(np.concatenate(values_list)) vp = sm.graphics.violinplot(values_list, ax = ax, labels = group_names, show_boxplot=False, plot_opts = { 'violin_fc':color , 'cutoff': True, 'cutoff_val': max_value, 'cutoff_type': 'abs'}) # Now plot the boxplot on top bp = plt.boxplot(values_list, sym='x') for key in bp.keys(): plt.setp(bp[key], color='black', lw=fontsize/10) # Adjust the power limits so that you use scientific notation on the y axis plt.ticklabel_format(style='sci', axis='y') ax.yaxis.major.formatter.set_powerlimits((-3,3)) plt.tick_params(axis='both', which='major', labelsize=fontsize) # Add the y label plt.ylabel(measure_name, fontsize=fontsize) # And now turn off the major ticks on the y-axis for t in ax.yaxis.get_major_ticks(): t.tick1On = False t.tick2On = False return ax
def draw_gene_isoforms(D, gene_id, outfile, outfmt): import matplotlib.patches as mpatches; from matplotlib.collections import PatchCollection; ISO = D[_.orig_gene == gene_id].GroupBy(_.alt_gene).Without(_.orig_gene, _.orig_exon_start, _.orig_exon_end).Sort(_.alt_gene); plt.cla(); y_loc = 0; y_step = 30; n_iso = ISO.alt_gene.Shape()(); origins = np.array([ [0, y] for y in xrange((y_step * (n_iso+1)),n_iso,-y_step) ]); patch_h = 10; xlim = [ ISO.exon_start.Min().Min()(), ISO.exon_end.Max().Max()()]; ylim = [ y_step, (y_step * (n_iso+1)) + 2*patch_h]; patches = []; for (origin, alt_id, starts, ends, exons, retention, alt5, alt3, skipped, new, ident) in zip(origins, *ISO()): plt.gca().text( min(starts), origin[1] + patch_h, alt_id, fontsize=10); for (exon_start, exon_end, exon_coverage, exon_retention, exon_alt5, exon_alt3, exon_skipped, exon_new, exon_ident) in zip(starts, ends, exons, retention, alt5, alt3, skipped, new, ident): if not(exon_skipped): patch = mpatches.FancyBboxPatch(origin + [ exon_start, 0], exon_end - exon_start, patch_h, boxstyle=mpatches.BoxStyle("Round", pad=0), color=draw_gene_isoforms_color(exon_retention, exon_alt5, exon_alt3, exon_skipped, exon_new, exon_ident)); text_x, text_y = origin + [ exon_start, +patch_h/2]; annots = zip(['Retention', "Alt 5'", "Alt 3'", "Skipped", 'New'], [exon_retention, exon_alt5, exon_alt3, exon_skipped, exon_new]); text = '%s: %s' %( ','.join([str(exid) for exid in exon_coverage]), '\n'.join([ s for (s,b) in annots if b])); plt.gca().text(text_x, text_y, text, fontsize=10, rotation=-45); plt.gca().add_patch(patch); if all(ident): plt.gca().plot([exon_start, exon_start], [origin[1], 0], '--k', alpha=0.3); plt.gca().plot([exon_end, exon_end], [origin[1], 0], '--k', alpha=0.3); #fi #fi #efor #efor plt.xlim(xlim); plt.ylim(ylim); plt.title('Isoforms for gene %s' % gene_id); plt.xlabel('Location on chromosome'); plt.gca().get_yaxis().set_visible(False); plt.gca().spines['top'].set_color('none'); plt.gca().spines['left'].set_color('none'); plt.gca().spines['right'].set_color('none'); plt.tick_params(axis='x', which='both', top='off', bottom='on'); plt.savefig(outfile, format=outfmt); return ISO;
def plot_pop_size_across_time(params, ymin=ymin, ymax=ymax): offset = step_size / 250. num_xticks = 11 ax = sns.tsplot(time="t", value="log2_pop_size", unit="sim_num", condition="policy", color=policy_colors, err_style="ci_band", ci=95, data=df, legend=False) for policy_num, policy in enumerate(policy_colors): error_df = summary_df[summary_df["policy"] == policy] c = policy_colors[policy] assert (len(error_df["t"]) == len(time_obj.t) == \ len(error_df["log2_pop_size"]["mean"])) plt.xlabel("Time step", fontsize=10) plt.ylabel("Pop. size ($\log_{2}$)", fontsize=10) # assuming glucose is listed first gluc_growth_rate = params["nutr_growth_rates"][0] galac_growth_rate = params["nutr_growth_rates"][1] if title is not None: plt.title(title, fontsize=8) else: plt.title(r"$P_{0} = %d$, " \ r"$\mu_{\mathsf{Glu}} = %.2f, \mu_{\mathsf{Gal}} = %.2f$, " \ r"$\mu_{\mathsf{Mis}} = %.2f$, lag = %d, " \ r"%d iters" %(init_pop_size, gluc_growth_rate, galac_growth_rate, params["mismatch_growth_rate"], params["decision_lag_time"], params["num_sim_iters"]), fontsize=8) c = 0.5 plt.xlim([min(df["t"]) - c, max(df["t"]) + c]) if ymin is None: ymin = int(np.log2(init_pop_size)) plt.ylim(ymin=ymin) plt.xlim([time_obj.t.min(), time_obj.t.max()]) plt.xticks(range(int(time_obj.t.min()), int(time_obj.t.max()) + x_step, x_step), fontsize=8) if yticks is not None: plt.yticks(yticks, fontsize=8) plt.ylim(yticks[0], yticks[-1]) sns.despine(trim=True, offset=2*time_obj.step_size) plt.tick_params(axis='both', which='major', labelsize=8, pad=2)
def plot_bar_plot(entropy_rates, filename, y_label): def_font_size = matplotlib.rcParams['font.size'] matplotlib.rcParams.update({'font.size': 25}) # entropy_rates = entropy_rates.T f, ax = plt.subplots(figsize=(20, 8)) hatch = ['-', 'x', '\\', '*', 'o', 'O', '.', '/'] * 2 #symbols = ['$\\clubsuit$', '$\\bigstar$', '$\\diamondsuit$', '$\\heartsuit', '$\\spadesuit$', '$\\blacksquare$'] symbols = ['O', 'E', 'D', 'I', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'] colors = ['blue', 'green', 'red', 'black', 'magenta', 'orange', 'gray'] * 2 num_ds = len(entropy_rates.columns) num_ticks = len(entropy_rates) width = 0.7 dataset_offset = width / num_ds space = 0.02 rects = list() for idx, (i, h, c, s) in enumerate(zip(entropy_rates.columns, hatch, colors, symbols)): pos = 0. - (width / 2) + idx * dataset_offset + idx * (space/2) pos = np.array([pos + idx for idx in xrange(num_ticks)]) # print idx, step, width #print pos #print width #print i rects.append( ax.bar(pos, entropy_rates[i], (width / num_ds - space), color='white', label=s + ': ' + i.decode('utf8'), lw=2, alpha=1., hatch=h, edgecolor=c)) autolabel(s, pos + (width / num_ds - space) / 2, entropy_rates[i], ax) # ax = entropy_rates[i].plot(position=pos,width=0.8, kind='bar',rot=20,ax=ax, alpha=1,lw=0.4,hatch=h,color=c) ax.set_position([0.1, 0.2, .8, 0.6]) plt.xticks(np.array(range(len(entropy_rates))), entropy_rates.index, rotation=0) ax.set_axisbelow(True) ax.xaxis.grid(False) ax.yaxis.grid(True, linewidth=3, alpha=0.2, ls='--') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) plt.tick_params(labelright=True) plt.legend(ncol=2, loc='upper center', bbox_to_anchor=(0.5, 1.35)) plt.ylim([min(list(entropy_rates.min())) * .95, max(list(entropy_rates.max())) * 1.05]) plt.ylabel(y_label) # plt.subplots_adjust(top=0.7) # plt.tight_layout() plt.savefig(filename, bbox_tight=True) plt.close('all') os.system('pdfcrop ' + filename + ' ' + filename) # plt.show() matplotlib.rcParams.update({'font.size': def_font_size})
def draw_out_put_digit(data, n, ans, recog): """ 学習済みのモデルが判定した画像を描画します. @param data 画像データ @param n 画像の通し番号 @param ans 正解ラベル @param recog 推定した数字 """ plt.subplot(10, 10, n) Z = data.reshape(SIZE, SIZE) Z = Z[::-1, :] plt.xlim(0, 27) plt.ylim(0, 27) plt.pcolor(Z) plt.title('ans=%d, recog=%d' % (ans, recog), size=8) plt.gray() plt.tick_params(labelbottom='off') plt.tick_params(labelleft='off')
def writeImage(fs, data, path): # 画像生成 # fs, data = read(WAVE_OUTPUT_FILENAME) cq_spec, freqs = cq_fft(data, fs) w, h = cq_spec.shape fig = pl.figure() fig.add_subplot(111) pl.imshow(abs(cq_spec).T, aspect = "auto", origin = "lower") pl.tick_params(labelbottom='off') pl.tick_params(labelleft='off') filepath = path + '/img.png' pl.savefig(filepath, bbox_inches='tight') # dumpを保存 raw_filepath = path + '/data.pkl' f = open(raw_filepath, 'w') pickle.dump(cq_spec, f) f.close()
def plot_bar_TiO2(): # TiO2 market_name = [ 'Household & Furniture', 'Automotive', 'Medical', 'Other Industries', 'Packaging', 'Electronics', 'Construction & Building' ] amount = [ 1468.35487751, 540.792628124, 1122.57862278, 833.309532892, 1137.82004151, 863.93634447, 3705.56984166 ] width = 0.15 last_num = 0 color = iter(cm.Set1(np.linspace(0, 1, 7))) for name, num in zip(market_name, amount): c = next(color) if name == 'Construction & Building': plt.bar(0.1, num, width, bottom=last_num, color=c, label=name, yerr=3000, error_kw=dict(ecolor='rosybrown', lw=2, capsize=5, capthick=2)) else: plt.bar(0.1, num, width, bottom=last_num, color=c, label=name) last_num += num plt.bar(0.7, 39600, width, color='salmon', label='Static Results (aggregated, all uses)') plt.legend(loc='upper left') plt.xlim(0, 1) plt.xticks((0.18, 0.78), ('Dynamic Model', 'Static Model')) plt.tick_params(labelsize=14) plt.show()
def plot_curve(timeseries): # Determine rolling statistics rolmean = timeseries.rolling(12, center=True).mean() rolstd = timeseries.rolling(12, center=True).std() #Plot rolling statistics: plt.figure(figsize=(15, 6)) plt.plot(timeseries, color='blue', label='time series data') plt.plot(rolmean, color='red', label='Rolling Mean') plt.plot(rolstd, color='black', label='Rolling Std') plt.title('Rolling Mean & Standard Deviation', size=18) plt.legend(loc='upper right', fontsize=13) plt.xlabel('Time', size=16) plt.ylabel('Unemployment Rate (%)', size=16) plt.tick_params(labelsize=13) plt.savefig('Rolling Mean & Standard Deviation', bbox_inches='tight', dpi=300, pad_inches=0.0) plt.show()
def plot_heap(stack, pointer=[], flip=True): mtrx = stack pntr = np.transpose([pointer]) if flip: mtrx = np.flipud(stack) pntr = np.flipud(np.transpose([pointer])) fig = plt.figure() if len(pntr > 0): gs = gridspec.GridSpec(1, 2) else: gs = gridspec.GridSpec(1, 1) ax1 = fig.add_subplot(gs[0, 0]) im = ax1.imshow(mtrx, interpolation='nearest', cmap=plt.cm.gray, vmin=0, vmax=1) if len(pntr > 0): ax2 = fig.add_subplot(gs[0, 1]) if len(pntr > 0): im = ax2.imshow(pntr, interpolation='nearest', cmap=plt.cm.gray, vmin=0, vmax=1) plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off') ax1.set_yticklabels(reversed(range(np.size(stack, axis=0)))) ax1.set_xticks(range(np.size(stack, axis=0))) ax1.set_yticks(range(np.size(stack, axis=1))) fig.tight_layout() fig.subplots_adjust(top=0.8) plt.colorbar(im) plt.show()
def plot_market_vintage(self,args='Total Release'): ''' Function to plot out the vintage results by markets This verion is going to plot out graph depending on the input arguments Total Release (defult): will plot out the total release (end of life + in use) for each market End of Life: will plot out the end of life release for each market ''' color=iter(cm.Set1(np.linspace(0,1,7))) if args == 'Total Release': fig,ax = plt.subplots(1) for each_mak, each_val in self.market_vintage_results.iteritems(): c=next(color) this_tot_release = each_val['Manufacturing Release']+each_val['In Use']+ each_val['End of Life'] ax.plot(self.years, this_tot_release,label = each_mak, linewidth = 2.5,c=c) #order legend handles, labels = ax.get_legend_handles_labels() handles = [handles[6],handles[0],handles[2],handles[3],handles[4],handles[5],handles[1]] labels = [labels[6], labels[0], labels[2],labels[3],labels[4],labels[5],labels[1]] ax.legend(handles,labels,loc='upper left') plt.xlabel('Year', fontsize=20, fontweight='bold') plt.ylabel('Total Releases in Tons', fontsize=20, fontweight='bold') plt.tick_params(labelsize=14) plt.show() elif args =='End of Life': plt.figure() for each_mak, each_val in self.market_vintage_results.iteritems(): plt.plot(self.years, each_val['End of Life'],label = each_mak) plt.legend(loc ='upper left') plt.xlabel('Year', fontsize=20, fontweight='bold') plt.ylabel('End of Life Releases in Tonnes', fontsize=20, fontweight='bold') plt.show() elif args =='In Use': plt.figure() for each_mak, each_val in self.market_vintage_results.iteritems(): plt.plot(self.years, each_val['In Use'],label = each_mak) plt.legend(loc ='upper left') plt.xlabel('Year', fontsize=20, fontweight='bold') plt.ylabel('In Use Releases in Tonnes', fontsize=20, fontweight='bold') plt.show()
def draw_field(bkx,bky,whx,why,bkhx,bkhy,whhx,whhy): fig=plt.figure() field=fig.add_subplot(111) plt.scatter(bkhx,bkhy,c='blue',s=50) plt.scatter(whhx,whhy,c='red',s=50) plt.scatter(bkx,bky,c='black',s=300) plt.scatter(whx,why,c='grey',s=300) plt.grid() plt.xlim(0,goban) plt.ylim(0,goban) plt.yticks(range(0,goban)) plt.xticks(np.array(range(0,goban)),alphabetU) field.set_xticklabels([]) field.set_yticklabels([]) field.xaxis.set_minor_locator(plt.FixedLocator(xtcks)) field.xaxis.set_minor_formatter(plt.FixedFormatter(alphabetU)) field.yaxis.set_minor_locator(plt.FixedLocator(ytcks)) field.yaxis.set_minor_formatter(plt.FixedFormatter(range(0,goban+1))) plt.tick_params(axis="x",which="minor",bottom="on",top="on") plt.show()
def draw_correlation(test_error, criterion, label, color="k", fontsize=24, isLegend=True): plt.figure(4, [8, 8]) plt.clf() indecies = utils.calc_min_list(criterion) plt.scatter(test_error[indecies], criterion[indecies], c=color, label=label) if isLegend: plt.legend(fontsize=fontsize) plt.xlabel("Generalization error", fontsize=fontsize) plt.ylabel("Error ratio", fontsize=fontsize) plt.tick_params(labelsize=fontsize) plt.tight_layout() plt.pause(0.01)
def plot_validation_correlations( experiment_name, model_name, dataset_name, epoch_start=0, epoch_end=200, description_dirname = 'Description', data_subset = 'validation_set.dat', scores_dir = 'validation', output_name = 'kendall_validation', datasets_path = '/home/lupoglaz/ProteinsDataset', models_dir = '/media/lupoglaz/3DCNN_MAQ_models'): proteins, decoys = read_dataset_description(os.path.join(datasets_path, dataset_name, description_dirname), data_subset) epochs = [0] taus = [0] pearsons = [0] losses = [1.0] for epoch in range(epoch_start, epoch_end+1): #print 'Loading scoring ',epoch input_path = '%s/%s_%s_%s/%s/epoch_%d.dat'%(models_dir, experiment_name, model_name, dataset_name, scores_dir, epoch) if os.path.exists(input_path): loss_function_values, decoys_scores = read_epoch_output(input_path) taus.append(get_kendall(proteins, decoys, decoys_scores)) pearsons.append(get_pearson(proteins, decoys, decoys_scores)) epochs.append(epoch) losses.append(get_average_loss(proteins, decoys, decoys_scores)) from matplotlib import pylab as plt fig = plt.figure(figsize=(4,4)) ax = fig.add_subplot(111) # plt.title(experiment_name+' '+model_name+' '+dataset_name) plt.plot(epochs,taus, '-.', color='black', label = 'Kendall tau') plt.plot(epochs,pearsons, '--',color = 'grey', label ='Pearson R') plt.plot(epochs,losses, '-', color='black', label ='Loss') # ax.annotate('Selected model', xy=(40, losses[40]), xytext=(30, losses[40] + 0.4), # arrowprops=dict(facecolor='black', shrink=0.05, width=2, headwidth = 5) # ) plt.ylabel('Validation loss and correlations',fontsize=16) plt.xlabel('Epoch',fontsize=14) plt.legend(prop={'size':10}) plt.tick_params(axis='x', which='major', labelsize=10) plt.tick_params(axis='y', which='major', labelsize=10) plt.tight_layout() plt.savefig('/media/lupoglaz/3DCNN_MAQ_models/%s_%s_%s/%s.png'%(experiment_name, model_name, dataset_name, output_name), format='png', dpi=1200) return taus, pearsons, losses
def draw_segments(*seg_width_color, figsize=(10, 10)): """seg_width_color is any number of tuples consisting of segments: np.array shape N,2,2, inner vals being [[start.x, start.y], [ end.x, end.y]] width: list or array length N color: a single matplotlib color specification """ with sns.axes_style("white"): fig, a = plt.subplots(figsize=figsize) for seg, width, color in seg_width_color: lc = LineCollection(seg, linewidths=width, color=color) a.add_collection(lc) a.set_xlim(-3, 3) a.set_ylim(-1, 11) # a.autoscale_view() plt.tick_params( axis='x', which='both', bottom='off', top='off', labelbottom='off') plt.tick_params( axis='y', which='both', left='off', right='off', labelleft='off')
def plot_rmsd(time,rmsd_backbone, rmsd_ligand): print('Plotting') fig = pl.figure( figsize =(50,10) ) print(str(len(rmsd_backbone))) print(str(len(rmsd_ligand))) print(str( len(time))) ax1 = fig.add_subplot(121) ax1.plot(time, rmsd_backbone, 'b-', label="backbone") ax1.plot(time, rmsd_ligand, 'r-', label="ligand") pl.xlabel(fig, fontsize=40) pl.ylabel(fig, fontsize=40) pl.tick_params(axis='both', which='major', labelsize=30) pl.tick_params(axis='both', which='minor', labelsize=30) ax1.legend(loc="best", fontsize=30) ax1.set_xlabel("time (ps)", fontsize=40) ax1.set_ylabel(r"RMSD ($\AA$)", fontsize=40) pl.rcParams.update({'font.size': 22}) ax1.set_title("RMSD vs time-step of backbone and ligand", fontsize=40) pl.show()
def plot_recall_vs_decision_boundary(t_recall_diab, t_recall_nodiab, filename='./img/Recall_score.png'): plt.figure(figsize=(10, 7)) plt.plot(np.arange(0, 1, 0.01), t_recall_diab, label='Diabetics') plt.plot(np.arange(0, 1, 0.01), t_recall_nodiab, label='Non-Diabetics') plt.plot([.5, .5], [0, 1], 'k--') plt.plot([.77, .77], [0, 1], 'k--') plt.ylim([0.0, 1.01]) plt.xlim([0.0, 1.0]) plt.legend(loc='upper left', fontsize=14) plt.title( 'Recall vs. Decision Boundary\n' 'using GradientBoostingClassifier', fontsize=14) plt.xlabel('Decision Boundary (T)', fontsize=14) plt.ylabel('Recall Rate', fontsize=14) plt.tick_params(axis='both', which='major', labelsize=14) plt.savefig(filename) plt.show()
def create_plot_with_style(x_size, y_size): plt.rcParams["figure.figsize"] = x_size, y_size fig, ax = plt.subplots() x_minor_locator = AutoMinorLocator(5) y_minor_locator = AutoMinorLocator(5) ax.xaxis.set_minor_locator(x_minor_locator) ax.yaxis.set_minor_locator(y_minor_locator) plt.tick_params(which="both", width=1.7) plt.tick_params(which="major", length=9) plt.tick_params(which="minor", length=5) ax.tick_params(axis="both", which="both", pad=8, left=True, right=True, top=True, bottom=True) fig.set_tight_layout(False) return fig, ax
def style_vr_plot(ax, x_max): ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(True) ax.spines['bottom'].set_visible(True) plt.tick_params( axis='both', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=True, # ticks along the bottom edge are off top=False, # ticks along the top edge are off right=False, left=True, labelleft=True, labelbottom=True) # labels along the bottom edge are off #ax.set_aspect('equal') ax.axvline(0, linewidth=2.5, color='black') # bold line on the y axis ax.axhline(0, linewidth=2.5, color='black') # bold line on the x axis plt.ylim(0, x_max) return ax
def plot_feature_loss(input_df, feature_name='cont1', num_bins=50): if feature_name.startswith('cont'): bins = np.linspace(0, 1.0, num_bins) feature_name_binned = feature_name + '_binned' input_df[feature_name_binned] = np.digitize(input_df[feature_name], bins=bins, right=True) input_df[ feature_name_binned] = input_df[feature_name_binned] / num_bins temp_dict = input_df.groupby( feature_name_binned)['loss'].mean().to_dict() temp_err_dict = input_df.groupby( feature_name_binned)['loss'].sem().to_dict() else: temp_dict = input_df.groupby(feature_name)['loss'].mean().to_dict() temp_err_dict = input_df.groupby(feature_name)['loss'].sem().to_dict() lists = sorted(temp_dict.items()) x, y = zip(*lists) lists_err = sorted(temp_err_dict.items()) x_err, y_error = zip(*lists_err) p.figure() plt.errorbar(x, y, fmt='o', yerr=y_error, label=feature_name) p.xlabel(feature_name, fontsize=20) p.ylabel('loss', fontsize=20) plt.tick_params(axis='both', which='major', labelsize=15) p.legend(prop={'size': 20}, numpoints=1, loc=(0.05, 0.8)) p.xlim([ input_df[feature_name].min() - 0.02, input_df[feature_name].max() + 0.02 ]) plt.grid() ax = plt.gca() plt.tick_params(axis='both', which='major', labelsize=15) ax.yaxis.set_major_locator(MaxNLocator(prune='lower')) ax.xaxis.set_major_locator(MaxNLocator(prune='lower')) ax.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))
def plotTaskPerformance(self, numRows=1, displayAvg=True): numCols = math.ceil( (len(self.taskNames.keys()) + displayAvg) / numRows) plt.figure(figsize=(5 * numCols, 5 * numRows)) plt.rcParams.update({'font.size': 20}) idx = 1 for taskId in self.taskNames.keys(): plt.subplot(numRows, numCols, idx) for i in range(len(self.expNames)): acc = self.accList[i][taskId] expName = self.expNames[i] plt.plot(acc, self.styles[i], color=self.colors[i], linewidth=3, label=expName) plt.xticks(range(len(self.taskOrder)), self.taskOrder) plt.xlabel('Task Arrival') plt.ylim(0, 1) if idx == 1 or idx == 4: plt.ylabel('Accuracy') else: plt.tick_params(labelleft=False) plt.grid(True) plt.title(self.taskNames[taskId]) idx += 1 if displayAvg == True: plt.subplot(numRows, numCols, idx) self.plotAvgPerformance(average_only=False) plt.tick_params(labelleft=False) #plt.legend(loc='upper center', fancybox=True, shadow=True, ncol=5) plt.tight_layout() #plt.legend(loc='upper center', bbox_to_anchor=(-3, 1.5), ncol = len(self.expNames)) plt.savefig('test_task.png') print('done')
def plot_roc(fpr, tpr, auc, ofname): ''' Function to plot the ROC curves (Receiver Characteristic Curves) INPUTS: fpr: False Positive rate tpr: True Positive Rate auc: Area under curve ofname: The directory to save the roc curve ''' plt.figure(figsize=figSize) plt.plot(fpr, tpr, lw=2.5, label='ROC curve (area = {0:0.2f})'.format(auc)) plt.xlabel("FPR",fontsize=fontSize) plt.ylabel("TPR",fontsize=fontSize) plt.ylim([0.0,1.01]) plt.tick_params(axis='both', labelsize=fontSize) plt.legend(loc="best",prop={'size':20},bbox_to_anchor=(1,0.15)) plt.tight_layout() ensure_dir(ofname) plt.savefig(ofname, bbox_inches='tight', pad_inches=0.1) #plt.show() plt.close()
def export(self, filename, limits=None): import matplotlib.pylab as plt plt.style.use('dark_background') if limits is None: xmin, xmax, ymin, ymax = self.get_limits() else: xmin, xmax, ymin, ymax = limits for x in range(xmin,xmax+1): plt.plot([x,x],[ymin,ymax],"w-") for y in range(ymin,ymax+1): plt.plot([xmin,xmax],[y,y],"w-") for x,y in self.alive: if xmin <= x < xmax and ymin <= y < ymax: plt.fill([x,x+1,x+1,x,x],[y,y,y+1,y+1,y],"w") plt.tick_params(axis='x',which='both',bottom='off',top='off',labelbottom='off') plt.tick_params(axis='y',which='both',left='off',right='off',labelleft='off') plt.axis("equal") plt.box("off") plt.savefig(filename) plt.clf()
def plot_diagr(self, namelist): """ Plots coefficient of linear regression for features :param namelist: list of parameter names in string format :return: None """ print('Plotting sorted correlations in diagram...') ticks = np.asarray(namelist) data = np.asarray([self.params_50per, self.params_2per, self.params_16per, self.params_84per, self.params_97per]) box = data[:,2:(self.ndim_blr + 2)] sort = np.argsort(np.mean(box,axis=0)) box_s = box[:,sort] plt.figure() plt.clf() bp = plt.boxplot(box_s, vert=False) set_box_color(bp, 'blue') plt.yticks(np.linspace(1,len(ticks), len(ticks)), ticks[sort]) plt.tick_params(axis='both', which='major', labelsize=12) plt.axvline(0, color='k', ls='--') plt.xlabel('Feature X-y Correlation') # plt.tight_layout() plt.subplots_adjust(left=0.3, right=0.95, top=0.9, bottom=0.1) plt.savefig(self.outmcmc + 'feature_y_correlation.png')
def plot_scores(title, scores, percentages, bar_color, font_color, facecolor): position = np.arange(len(scores)) fontsize = 125 / len(scores) fig, ax = plt.subplots(facecolor=facecolor) ax.set_facecolor(facecolor) plt_title = 'Ability Rolls ' + title plt.title(plt_title, fontsize=25) plt.xticks(position, scores, fontsize=fontsize) plt.ylabel('Frequency', fontsize=15) plt.xlabel('Score', fontsize=15) for spine in plt.gca().spines.values(): spine.set_visible(False) plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on') bars = plt.bar(position, percentages, align='center', color=bar_color) max_height = max([bari.get_height() for bari in bars]) for bari in bars: color = font_color height = bari.get_height() - max_height * fontsize / 250 if height < fontsize / 1000: height = bari.get_height() + max_height * fontsize / 3 / 250 color = 'black' plt.gca().text(bari.get_x() + bari.get_width() / 2, height, str(int(height * 100)) + '%', ha='center', color=color, fontsize=fontsize) plt.tight_layout() fig.savefig(plt_title + '.png', facecolor=facecolor, edgecolor='none') plt.close()
def plot_confusion_matrix(cm, cmap=plt.cm.Blues): classes = ['airplane', 'bathtub', 'bed', 'bench', 'bookshelf', 'bottle', 'bowl', 'car', 'chair', 'cone', 'cup', 'curtain', 'desk', 'door', 'dresser', 'flower_pot', 'glass_box', 'guitar', 'keyboard', 'lamp', 'laptop', 'mantel', 'monitor', 'night_stand', 'person', 'piano', 'plant', 'radio', 'range_hood', 'sink', 'sofa', 'stairs', 'stool', 'table', 'tent', 'toilet', 'tv_stand', 'vase', 'wardrobe', 'xbox'] plt.rcParams['savefig.dpi'] = 300 #图片像素 plt.rcParams['figure.dpi'] = 300 #分辨率 # plt.figure(figsize=(20, 20)) fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) plt.tick_params(labelsize=5) # We want to show all ticks... ax.set( xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes) plt.title('Confusion matrix', fontsize=6) plt.xlabel('Predicted label', fontsize=6) plt.ylabel('True label', fontsize=6) # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], 'd'), ha="center", va="center", fontsize=3, color="white" if cm[i, j] > thresh else "black") fig.tight_layout() plt.savefig('conf_mtx.png')
def energy_plot(energyList): ''' This part of code uses matplotlib.pylab to plot ground state energy per site versus square of inverse chain length. Results are extrapolated to thermodynamic limit using linear fit, polynomial fit of degree one from numpy. ''' plt.close('all') plt.figure(figsize=(8, 6)) plt.title("$E_0/N$ versus $1/N^2$", fontsize=18) # plot for odd number of system size x1 = [1.0 / x[0]**2 for x in energyList if x[0] % 2 == 1] y1 = [x[1] for x in energyList if x[0] % 2 == 1] #Polynomail fit of degree 1 is a linear fit m1, c1 = np.polyfit(x1, y1, deg=1) #m1 and c1 are slope and intercept of equation y1=m1*x1+c1 poly1 = m1 * np.array(x1) + c1 plt.plot(x1, poly1, color='red', lw=2) plt.plot(x1, y1, 'mo', ms=8, label='Odd $E_0/N$= %1.6f' % c1) # plot for even number of system size x2 = [1.0 / x[0]**2 for x in energyList if x[0] % 2 == 0] y2 = [x[1] for x in energyList if x[0] % 2 == 0] m2, c2 = np.polyfit(x2, y2, deg=1) poly2 = m2 * np.array(x2) + c2 plt.plot(x2, poly2, color='blue', lw=2) plt.plot(x2, y2, 'kD', ms=7, label='Even $E_0/N$= %1.6f' % c2) plt.ylabel('Ground State Energy Per Site $(E_0/N)$', fontsize=14) plt.xlabel('Square of Inverse Chain Length,$1/N^2$', fontsize=14) plt.tick_params(labelsize=12) plt.legend(loc=4) #plt.savefig('Adhikari_Khagen_Mid_Term_Project_Plot.pdf') plt.tight_layout() plt.show()
def plot_spectrograms(bsl,rec,rate,title): plt.close() plt.rc('font', family='Arial') fig, ax = plt.subplots(nrows=9, ncols=2, sharex='col', sharey='row') fig.suptitle(title + " - REM stage", fontsize=20) plt.subplots_adjust(wspace = .05,hspace = 0.4 ) ny_nfft=1024 i=0 plt.tick_params(axis='both', labelsize=8) while i<9: Pxx, freq, bins, im = ax[i,0].specgram(bsl[i],NFFT=ny_nfft,Fs=rate) ax[i,0].set_yticks(np.arange(0, 50, 10)) ax[i,0].set_ylim([0, 40]) if(i==8): ax[i,0].set_xlabel("Time, seconds", fontsize=10) ax[i,0].set_ylabel("Freq, Hz", fontsize=8) ax[i,0].set_title('Baseline, channel:'+str(i+1), fontsize=10) for label in (ax[i,0].get_xticklabels() + ax[i,0].get_yticklabels()): label.set_fontname('Arial') label.set_fontsize(8) i=i+1 i=0 while i<9: Pxx, freq, bins, im = ax[i,1].specgram(rec[i],NFFT=ny_nfft,Fs=rate) ax[i,0].set_yticks(np.arange(0, 50, 10)) ax[i,1].set_ylim([0, 40]) #ax[i,1].set_xlim([0, 10000]) #13000]) if(i==8): ax[i,1].set_xlabel("Time, seconds", fontsize=10) #ax[i,1].set_ylabel("Freq, Hz") ax[i,1].set_title('Recovery, channel:'+str(i+1), fontsize=10) for label in (ax[i,0].get_xticklabels() + ax[i,0].get_yticklabels()): label.set_fontname('Arial') label.set_fontsize(8) i=i+1 plt.show() return
def plot_bar_TiO2(): # TiO2 market_name = ['Household & Furniture','Automotive','Medical','Other Industries','Packaging','Electronics', 'Construction & Building'] amount = [1468.35487751, 540.792628124, 1122.57862278, 833.309532892, 1137.82004151, 863.93634447, 3705.56984166] width = 0.15 last_num = 0 color=iter(cm.Set1(np.linspace(0,1,7))) for name,num in zip(market_name,amount): c=next(color) if name == 'Construction & Building': plt.bar(0.1,num,width,bottom=last_num,color=c,label=name,yerr=3000,error_kw=dict(ecolor='rosybrown', lw=2, capsize=5, capthick=2)) else: plt.bar(0.1,num,width,bottom=last_num,color=c,label=name) last_num += num plt.bar(0.7,39600,width,color='salmon',label = 'Static Results (aggregated, all uses)') plt.legend(loc='upper left') plt.xlim(0,1) plt.xticks((0.18,0.78), ('Dynamic Model','Static Model')) plt.tick_params(labelsize=14) plt.show()
def optimsation_curve(history_, plot_dir1, plot_dir2, show=True): ''' Function to plot the accuracy and loss during training and validation INPUTS: history_: The log history of the fully trained model plot_dir1: The directory to save accuracy curves plot_dir2: The directory to save the loss curves ''' plt.figure(figsize=figSize) plt.plot(history_.history['acc'], c='r', lw=2.5, label='Training') plt.plot(history_.history['val_acc'], c='b', lw=2.5, label='validation') plt.xlabel('Epoch', fontsize=fontSize) plt.ylabel('Accuracy', fontsize=fontSize) plt.tick_params(axis='both', labelsize=fontSize) plt.legend(loc="best", prop={'size': 14}, bbox_to_anchor=(1, 0.5)) plt.tight_layout() ensure_dir(plot_dir1) plt.savefig(plot_dir1, bbox_inches='tight', pad_inches=0.1) if show: plt.show() plt.close() plt.figure(figsize=figSize) plt.plot(history_.history['loss'], c='r', lw=2.5, label='Training') plt.plot(history_.history['val_loss'], c='b', lw=2.5, label='validation') plt.xlabel('Epoch', fontsize=fontSize) plt.ylabel('Loss', fontsize=fontSize) plt.tick_params(axis='both', labelsize=fontSize) plt.legend(loc="best", prop={'size': 14}, bbox_to_anchor=(1, 0.5)) plt.tight_layout() ensure_dir(plot_dir2) plt.savefig(plot_dir2, bbox_inches='tight', pad_inches=0.1) if show: plt.show() plt.close()
def plot_posterior(self, limit=30, fname=None, fmat='eps'): '''plots posterior across models Parameters ---------- limit : int the top most models to plot fname : str filename to save the figure, default is None and shows the figure ''' posterior = self['fit']['posterior'].ix[:limit] plt.bar(left=range(1, len(posterior) + 1), height=posterior, color='k') plt.xlabel('Model by Rank Order', fontsize=15) plt.ylabel('Posterior Probability', fontsize=15) plt.tick_params(axis='both', labelsize=15, \ top='off', right='off') plt.text(x=plt.xlim()[1]*1./2, y=plt.ylim()[1]*8.5/10, \ s=('{}{}\n{}{:,.0f}'.format(\ 'Models Shown: ', min(self.data.shape[0], limit), \ 'Models Estimated: ', \ self.data.shape[0])), fontsize=10) if fname is None: plt.show() else: plt.savefig('{}.{}'.format(fname, fmat), bbox_inches='tight') plt.clf() plt.close()
def get_scatterplot(self, xaxis='e_above_hull_input', yaxis='e_above_hull_ce'): """ plots two attributes. Some useful pairs: xaxis='e_above_hull_input', yaxis='e_above_hull_ce' xaxis='normalized_energies', yaxis='normalized_ce_energies' xaxis='e_above_hull_input', yaxis='normalized_error' """ textstr = '\n'.join(( r'$RMSE = %.3f eV/prim$'%(self.rmse,), r'$CV Score = %.3f$'%(self.cv,), r'$N_{strs} = %d$'%len(self.items) )) plt.figure(figsize=(8.0,6.0)) plt.scatter(self.__getattribute__(xaxis), self.__getattribute__(yaxis),label=textstr) fs = 18 fst = 14 plt.tick_params(labelsize=fst) plt.xlabel(xaxis,fontsize=fs) plt.ylabel(yaxis,fontsize=fs) plt.legend(fontsize=fs) #props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) #plt.title(textstr,fontsize=fs) return plt
def custom_plot_local(): se3_loss_tr, se3_loss_val = get_training_losses(experiment = 'LocalSE3MultiResReprScalar', max_epoch=150) e3_loss_tr, e3_loss_val = get_training_losses(experiment = 'LocalE3MultiResRepr4x4', max_epoch=150) f = plt.figure(figsize=(6,4)) plt.plot(se3_loss_tr[1], '.-', label='SE(3) training') plt.plot(se3_loss_val, '.-', label='SE(3) validation') plt.plot(e3_loss_tr[1], '--', label='ConvNet training') plt.plot(e3_loss_val, '--', label='ConvNet validation') ax = plt.gca() plt.yscale('log') ax.set_yticks([1.0, 0.8, 0.6, 0.4, 0.2, 0.1]) ax.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) plt.xlabel('Epoch number',fontsize=16) plt.ylabel('Ranking loss',fontsize=16) plt.legend(prop={'size':16}) plt.tick_params(axis='x', which='major', labelsize=10) plt.tick_params(axis='y', which='major', labelsize=10) plt.ylim([0.0, 1.0]) plt.tight_layout() plt.legend() plt.savefig('Fig/Total_training.png', format='png', dpi=600) sys.exit()
def OpenPlot(self): def getspec(self): global x global y ftypes = [('Data files', '*.dat'), ('All files', '*')] dlg = tkFileDialog.Open(self, filetypes = ftypes) fl = dlg.show() if fl != '': f = open(fl) data = np.loadtxt(f) x = data[:,0] y = data[:,1] getspec(self) minorLocator = AutoMinorLocator() golden = (plt.sqrt(5) + 1.)/2. figprops = dict(figsize = (6., 6./golden), dpi = 128) adjustprops = dict(left = 0.15, bottom = 0.20, right = 0.90, top = 0.93, wspace = 0.2, hspace = 0.2) MyPlot = plt.figure(1, **figprops) MyPlot.subplots_adjust(**adjustprops) plt.clf() MySubplot = MyPlot.add_subplot(1, 1, 1) MySubplot.plot(x,y) plt.xlabel('$\lambda$ ($\AA$)', fontsize = 18) plt.ylabel('$F_\lambda$ ($10^{-17}$ erg/$cm^2$/s/$\AA$)', fontsize = 18) axes = plt.gca() plt.tick_params(which = 'both', width = 2) plt.tick_params(which = 'major', length = 4) plt.tick_params(which = 'minor', length = 4, color = 'r') MySubplot.xaxis.grid(True, which = "both") plt.ticklabel_format(style = 'sci', axis = 'x', scilimits = (0,0)) MySubplot.xaxis.set_minor_locator(minorLocator) print("Done!")
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) ; label = ttk.Label(self, text = "Spectra App", font = LARGE_FONT) ; label.pack(pady = 10, padx = 10) ; button1 = ttk.Button(self, text = "Back to Start", command = lambda: controller.show_frame(StartPage)); button1.pack() ; self.minorLocator = AutoMinorLocator(); golden = (plt.sqrt(5) + 1.)/2. ; figprops = dict(figsize = (6., 6./golden), dpi = 128) ; adjustprops = dict(left = 0.15, bottom = 0.20, right = 0.90, top = 0.93, wspace = 0.2, hspace = 0.2) ; self.plot = plt.figure(1, **figprops) ; self.plot.subplots_adjust(**adjustprops) ; plt.clf () ; self.subplot = self.plot.add_subplot(1, 1, 1) ; self.subplot.plot([1,2,3,4,5],[3,4,5,6,7]) plt.xlabel('$\lambda$ ($\AA$)', fontsize=18) ; plt.ylabel('$F_\lambda$ ($10^{-17}$ erg/$cm^2$/s/$\AA$)', fontsize=18) ; axes = plt.gca() ; plt.tick_params(which = 'both', width = 2) ; plt.tick_params(which = 'major', length = 4) ; plt.tick_params(which = 'minor', length = 4, color = 'r') ; plt.close(self.plot) ; canvas = FigureCanvasTkAgg(self.plot, self) ; canvas.show() ; canvas.get_tk_widget().pack(side = tk.BOTTOM, fill = tk.BOTH, expand = True) ; toolbar = NavigationToolbar2TkAgg(canvas, self) ; toolbar.update() canvas._tkcanvas.pack(side = tk.TOP, fill = tk.BOTH, expand = True) ;
def render_lineplot(outf, plotdata, title, note): """ Renders a lineplot to PDF. This function is presently used to generate PCB pricing graphs by :mod:`tendril.dox.gedaproject.gen_pcbpricing`. It's pretty unwieldy, and is likely going to be axed at some point in favor of :func:`make_graph`, once the necessary functionality is implemented there and the pricing graph code is modified to use that instead. .. warning:: This function is likely to be deprecated. .. seealso:: :func:`make_graph` :param outf: The path to the output file. :param plotdata: The data to plot. :param title: The title of the plot. :param note: An additional note to include with the plot (not implemented) :return: outf """ curvenames = [] ylists = [] xlists = [] for x, y in iteritems(plotdata): for name, value in iteritems(y): if name not in curvenames: curvenames.append(name) xlists.append([]) ylists.append([]) curveindex = curvenames.index(name) xlists[curveindex].append(x) ylists[curveindex].append(value) import matplotlib.pylab as pl pl.figure(1, figsize=(11.69, 8.27)) ax = pl.subplot(111) ax.spines["top"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() try: ymax = max([max(l) for l in ylists]) except ValueError: print(ylists) raise ValueError xmin = min([min(l) for l in xlists]) xmax = max([max(l) for l in xlists]) pl.yticks(range(0, int(ymax), int(ymax / 10)), [str(x) for x in range(0, int(ymax), int(ymax / 10))]) for y in range(0, int(ymax), int(ymax / 10)): ax.plot(range(xmin, xmax), [y] * len(range(xmin, xmax)), "--", lw=0.5, color="black", alpha=0.3) pl.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="off", right="off", labelleft="on") pl.ylim(0, ymax) pl.xlim(xmin, xmax) for idx, curvename in enumerate(curvenames): ax.plot(xlists[idx], ylists[idx], color=tableau20[idx], label=curvename) # y_pos = ylists[idx][-1] - 0.5 # pl.text(xmax, y_pos, curvename, color=tableau20[idx]) pl.title(title) pl.legend() pl.savefig(outf, format='pdf') pl.clf() return outf
R_star, transit_duration, [planet, firstmoon, secondmoon, thirdmoon]) # Output information print 'TTV amplitude =', numpy.amax(ttv_array), \ '[min] = ', numpy.amax(ttv_array) * 60, '[sec]' print 'TDV amplitude =', numpy.amax(tdv_array), \ '[min] = ', numpy.amax(tdv_array) * 60, '[sec]' ax = plt.axes() plt.plot(ttv_array, tdv_array, color = 'k') plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) plt.rc('text', usetex=True) plt.tick_params(axis='both', which='major', labelsize = 16) plt.xlabel('transit timing variation [minutes]', fontsize = 16) plt.ylabel('transit duration variation [minutes]', fontsize = 16) ax.tick_params(direction='out') plt.ylim([numpy.amin(tdv_array) * 1.2, numpy.amax(tdv_array) * 1.2]) plt.xlim([numpy.amin(ttv_array) * 1.2, numpy.amax(ttv_array) * 1.2]) plt.plot((0, 0), (numpy.amax(tdv_array) * 10., numpy.amin(tdv_array) * 10.), 'k', linewidth=0.5) plt.plot((numpy.amin(ttv_array) * 10., numpy.amax(ttv_array) * 10.), (0, 0), 'k', linewidth=0.5) # Fix axes for comparison with eccentric moon plt.xlim(-0.15, +0.15) plt.ylim(-0.65, +0.65) plt.annotate(r"5:4:3", xy=(-0.145, +0.55), size=16) plt.savefig("fig_system_16.eps", bbox_inches = 'tight')
fig = plt.figure(1, figsize=(9, 6)) # Create an axes instance ax = fig.add_subplot(111) # Create the boxplot bp = ax.boxplot([data_to_plot], 0, 'rD') for _, line_list in bp.items(): for line in line_list: line.set_color(cmap(50)) plt.xlabel("Edge") plt.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off top=False, # ticks along the top edge are off labelbottom=False) # labels along the bottom edge are off plt.ylabel("Edge length [µm]") plt.title( "Edge length statistics: n = %i (mean: %f / std. dev.: %f / outliers: %i)" % (n, mean, sd, outliers)) plt.suptitle("Cell: (%s) %s" % ("Original", filename[0:-4])) x_coordinates = [-1, 2] y_coordinates = [2, 2] plt.plot(x_coordinates, y_coordinates, color=cmap(0)) plt.grid(True) fig = plt.figure(2, figsize=(9, 6)) ax = fig.add_subplot(111)
# Please run the simulations for all of the three activations before doing this step ranges = [0,100] graphs_raw = [graph_relu, graph_elu, graph_tanh] colors = ['r', 'b', 'g'] labels = ['relu', 'elu', 'tanh'] # Getting CI for each graph with lower quantile 5% and upper quantile 95% graphs = [mean_CI(np.array(graph), 5, 95, ranges) for graph in graphs_raw] #define a function that plots mean and CI def plot_mean_and_CI(mean, lower, upper, label, color_mean=None, color_shading=None): plt.fill_between(range(len(mean)), upper, lower, color = color_shading, alpha=.5) plt.plot(mean, color_mean, linestyle='--', label=label) # Plotting graphs with CI plt.style.use('ggplot') fig = plt.figure(figsize=(10,6)) for i in range(len(graphs)): plot_mean_and_CI(graphs[i][2], graphs[i][0], graphs[i][1], labels[i], color_mean=colors[i], color_shading = colors[i]) plt.xlabel('epoch', fontsize=20) plt.ylabel('Validation Accuracy', fontsize=20) plt.legend(loc='lower right', fontsize=19) plt.tick_params(labelsize=13) plt.rcParams['axes.axisbelow'] = True leg = plt.legend(loc='lower right', fontsize=19, shadow=True, facecolor='white')
os.chdir("../") plt.figure(figsize=(18.5,10.5)) ax = plt.subplot(1,1,1) #-------------------------------------------------------------------- ax.tick_params(axis='x', pad=15) # distance between axis and text ax.tick_params(axis='y', pad=15) #-------------------------------------------------------------------- ax.spines['left'].set_linewidth(3.0) ax.spines['right'].set_linewidth(3.0) ax.spines['top'].set_linewidth(3.0) ax.spines['bottom'].set_linewidth(3.0) #=================================================================================== plt.minorticks_on() plt.tick_params(which='major',direction='in',width=3.0,length=12) # plt.tick_params(which='minor',direction='in',width=3.0,length=5) plt.xticks(fontsize=30) plt.yticks(fontsize=30) #----------------------------------------------------------------------------------- # plot data #----------------------------------------------------------------------------------- plt.scatter(dipole[:,1], dipole[:,0], s=200) # x axis is z coordinate, y axis is y coordinate plt.scatter(jog[:,1], jog[:,0], s=200) plt.xlim(0,84.36) plt.xlabel(r'$z\ \mathrm{(\AA)}$', fontsize='35') plt.ylabel(r'$y\ \mathrm{(\AA)}$', fontsize='35')
def spatial(aCGH, signal=None, title=None, median_center=False, cmap=None, cbticks=None): """ Produces the *spatial* plot, which is a representation of the chip as it was scanned. Parameters ---------- aCGH : :class:`pycgh.datatypes.ArrayCGH` The object representing the Array CGH. signal : array_like, optional (default: None) The signal representing the log 2 ratio of the intensities of the test and the reference signal. If not provided, it is reconstructed using the test and reference signal contained in the aCGH object. title : str, optional (default: None) The title assigned to the plot. If None, it is automatically set to 'CGH Spatial plot'. median_center : bool, optional (default: False) If set to True, the median of the signal is subtracted by the image. cmap : :class:`matplotlib.colors.Colormap`, optional (default: None) The color map to be passed to the actual plotting function. cbticks : array_like, optional (default: None) The *ticks* in the color bar. If None, the color bar is divided in 9 equal parts, including all values (colors) present in the plot. """ plt.title('CGH Spatial plot' if title is None else title, size=8) print cbticks #raise Exception() rows = aCGH.F['row'] cols = aCGH.F['col'] if signal is None: signal = (np.log2(aCGH.F['test_signal']) - np.log2(aCGH.F['reference_signal'])) try: array_image = signal.reshape((rows.max(), cols.max())) except ValueError: array_image = np.ones((rows.max(), cols.max())) * np.nan for r, c, sig in zip(rows, cols, signal): array_image[r - 1, c - 1] = sig if median_center: array_image -= np.median(array_image[~np.isnan(array_image)]) vmin = np.nanmin(array_image) vmax = np.nanmax(array_image) xlabel, ylabel = 'columns', 'rows' r, c = array_image.shape if r > c: array_image = array_image.T xlabel, ylabel = ylabel, xlabel plt.tick_params(axis='both', direction='out', length=3, colors='black', labelsize='small', labelbottom='on') plt.imshow(array_image, cmap=plt.cm.jet if cmap is None else cmap, aspect='equal', interpolation='nearest', norm=None, vmin=vmin, vmax=vmax) plt.xlabel(xlabel) plt.ylabel(ylabel) ticks = np.linspace(vmin, vmax, 10) if cbticks is None else np.asarray(cbticks) fmt = '%d' if ticks.dtype == np.int else '%.2f' cb = plt.colorbar(orientation='horizontal', ticks=ticks, boundaries=cbticks, aspect=40, format=fmt, spacing='proportional') cb.ax.tick_params(axis='x', direction='out', length=3, colors='black', labelsize='small')
# Run simulation. Make sure to add/remove the moons you want to simulate! ttv_array, tdv_array = run_sim(R_star, transit_duration, [planet, firstmoon, secondmoon]) # Output information print 'TTV amplitude =', numpy.amax(ttv_array), \ '[min] = ', numpy.amax(ttv_array) * 60, '[sec]' print 'TDV amplitude =', numpy.amax(tdv_array), \ '[min] = ', numpy.amax(tdv_array) * 60, '[sec]' ax = plt.axes() plt.plot(ttv_array, tdv_array, color='k') plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) plt.rc('text', usetex=True) plt.tick_params(axis='both', which='major', labelsize=16) plt.xlabel('transit timing variation [minutes]', fontsize=16) plt.ylabel('transit duration variation [minutes]', fontsize=16) ax.tick_params(direction='out') plt.ylim([numpy.amin(tdv_array) * 1.2, numpy.amax(tdv_array) * 1.2]) plt.xlim([numpy.amin(ttv_array) * 1.2, numpy.amax(ttv_array) * 1.2]) plt.plot((0, 0), (numpy.amax(tdv_array) * 10., numpy.amin(tdv_array) * 10.), 'k', linewidth=0.5) plt.plot((numpy.amin(ttv_array) * 10., numpy.amax(ttv_array) * 10.), (0, 0), 'k', linewidth=0.5) # Fix axes for comparisons plt.xlim(-0.2, +0.2) plt.ylim(-0.5, +0.5)
urllib.urlretrieve(url_azam,'suominet/AZAMnrt_%s.txt' %year) urllib.urlretrieve(url_kitt,'suominet/KITTnrt_%s.txt' %year) azam = lf.suominet('suominet/AZAMnrt_%s.txt' %year) kitt = lf.suominet('suominet/KITTnrt_%s.txt' %year) ax[0].errorbar(24*(azam[0]-gtime[0]),*azam[1:3],label='Amado',fmt='o',color='blue',ecolor='blue',ms=0,elinewidth=4,capsize=6) ax[0].errorbar(24*(kitt[0]-gtime[0]),*kitt[1:3],label='Kitt Peak',fmt='o',color='red',ecolor='red',ms=0,elinewidth=4,capsize=6) if night == 'n20161204': leg = ax[0].legend(loc='best',prop={'size':20}) #leg.get_frame().set_alpha(0) leg2 = ax[1].legend(loc=4,prop={'size':20}) #leg2.get_frame().set_alpha(0) # Formatting plt.rcParams.update({'font.size': 22}) plt.tick_params('both', length=5, width=1, which='minor') plt.tick_params('both', length=10, width=1, which='major') ax[1].tick_params(axis='x', pad=8) #yticks2 = [0.24,0.26,0.28] yticks2 = [2.6,2.8,3.0] ax[2].set_yticks(yticks2) yticks1 = [0.60,0.65,0.70,0.75] ax[1].set_yticks(yticks1) yticks0 = [0,4,8,12,16] ax[0].set_yticks(yticks0) plt.subplots_adjust(bottom=0.14, left = 0.15,hspace=0) #ax[0].set_title(night) ax[0].text(0.5,14,night) ax[0].set_ylim(0,18) ax[0].grid(True) ax[1].grid(True)
def plot_fit(par, lbd, logF, dlogF, minfo, listpar, lbdarr, logF_grid, isig, dims, Nwalk, Nmcmc, par_list, ranges, include_rv, npy, log_scale): ''' Plots best model fit over data Usage: plot_fit(par, lbd, logF, dlogF, minfo, logF_grid, isig, Nwalk, Nmcmc) where par = np.array([Mstar, oblat, Sig0, Rd, n, cosi, dist]) ''' # model parameters if include_rv is True: Mstar, oblat, Hfrac, cosi, dist, ebv, rv = par lim = 3 lim2 = 2 else: Mstar, oblat, Hfrac, cosi, dist, ebv = par lim = 2 lim2 = 1 rv = 3.1 # Rpole, Lstar, Teff = vkg.geneve_par(Mstar, oblat, Hfrac, folder_tables) # t = np.max(np.array([hfrac2tms(hfrac), 0.])) t = np.max(np.array([hfrac2tms(Hfrac), 0.])) Rpole, logL = geneva_interp_fast(Mstar, oblat, t, neighbours_only=True, isRpole=False) norma = (10. / dist)**2 # (Lstar*Lsun) / (4. * pi * (dist*pc)**2) uplim = dlogF == 0 keep = np.logical_not(uplim) # chain = np.load(npy) # interpolate models logF_mod = griddataBA(minfo, logF_grid, par[:-lim], listpar, dims) logF_list = np.zeros([len(par_list), len(logF_mod)]) chi2 = np.zeros(len(logF_list)) for i in range(len(par_list)): logF_list[i] = griddataBA(minfo, logF_grid, par_list[i, :-lim], listpar, dims) # convert to physical units logF_mod += np.log10(norma) logF_list += np.log10(norma) for j in range(len(logF_list)): chi2[j] = np.sum( (logF[keep] - logF_list[j][keep])**2 / (dlogF[keep])**2) # chib = chi2[np.argsort(chi2)[-30:]] / max(chi2) flux = 10.**logF dflux = dlogF * flux flux_mod = 10.**logF_mod flux_mod = pyasl.unred(lbd * 1e4, flux_mod, ebv=-1 * ebv, R_V=rv) # Plot definitions bottom, left = 0.75, 0.48 width, height = 0.96 - left, 0.97 - bottom plt.axes([left, bottom, width, height]) # plot fit if log_scale is True: for i in range(len(par_list)): if i % 80 == 0: ebv_temp = np.copy(par_list[i][-lim2]) F_temp = pyasl.unred(lbd * 1e4, 10**logF_list[i], ebv=-1 * ebv_temp, R_V=rv) plt.plot(lbd, lbd * F_temp, color='gray', alpha=0.1) plt.errorbar(lbd, lbd * flux, yerr=lbd * dflux, ls='', marker='o', alpha=0.5, ms=10, color='blue', linewidth=2) plt.plot(lbd, lbd * flux_mod, color='red', ls='-', lw=3.5, alpha=0.4, label='$\mathrm{Best\, fit}$') plt.xlabel('$\lambda\,\mathrm{[\mu m]}$', fontsize=20) plt.ylabel(r'$\lambda F_{\lambda}\,\mathrm{[erg\, s^{-1}\, cm^{-2}]}$', fontsize=20) plt.yscale('log') else: for i in range(len(par_list)): if i % 80 == 0: ebv_temp = np.copy(par_list[i][-lim2]) F_temp = pyasl.unred(lbd * 1e4, 10**logF_list[i], ebv=-1 * ebv_temp, R_V=rv) plt.plot(lbd, F_temp, color='gray', alpha=0.1) plt.errorbar(lbd, flux, yerr=lbd * dflux, ls='', marker='o', alpha=0.5, ms=10, color='blue', linewidth=2) plt.plot(lbd, flux_mod, color='red', ls='-', lw=3.5, alpha=0.4, label='$\mathrm{Best\, fit}$') plt.xlabel('$\lambda\,\mathrm{[\mu m]}$', fontsize=20) plt.ylabel(r'$F_{\lambda}\,\mathrm{[erg\, s^{-1}\, cm^{-2} \mu m]}$', fontsize=20) plt.xlim(min(lbd), max(lbd)) plt.tick_params(direction='in', length=6, width=2, colors='gray', which='both') plt.legend(loc='upper right') return
def plot_residuals(par, lbd, logF, dlogF, minfo, listpar, lbdarr, logF_grid, isig, dims, Nwalk, Nmcmc, ranges, include_rv, npy, log_scale, model): ''' Plots best model fit over data Usage: plot_fit(par, lbd, logF, dlogF, minfo, logF_grid, isig, Nwalk, Nmcmc) where par = np.array([Mstar, oblat, Sig0, Rd, n, cosi, dist]) ''' # model parameters if include_rv is True: Mstar, oblat, Hfrac, cosi, dist, ebv, rv = par lim = 3 lim2 = 2 else: if model == 'befavor': Mstar, oblat, Hfrac, cosi, dist, ebv = par if model == 'aara' or model == 'acol' or model == 'bcmi': Mstar, oblat, Hfrac, Sig0, Rd, n, cosi, dist, ebv = par if model == 'beatlas': Mstar, oblat, Sig0, n, cosi, dist, ebv = par Hfrac = 0.3 lim = 2 lim2 = 1 rv = 3.1 # Rpole, Lstar, Teff = vkg.geneve_par(Mstar, oblat, Hfrac, folder_tables) # t = np.max(np.array([hfrac2tms(hfrac), 0.])) t = np.max(np.array([hfrac2tms(Hfrac), 0.])) Rpole, logL = geneva_interp_fast(Mstar, oblat, t, neighbours_only=True, isRpole=False) norma = (10. / dist)**2 # (Lstar*Lsun) / (4. * pi * (dist*pc)**2) uplim = dlogF == 0 keep = np.logical_not(uplim) # *** chain = np.load(npy) par_list = chain[:, -1, :] # interpolate models if model == 'beatlas': logF_mod = griddataBAtlas(minfo, logF_grid, par[:-lim], listpar, dims, isig) else: logF_mod = griddataBA(minfo, logF_grid, par[:-lim], listpar, dims) logF_list = np.zeros([len(par_list), len(logF_mod)]) chi2 = np.zeros(len(logF_list)) for i in range(len(par_list)): if model == 'beatlas': logF_list[i] = griddataBAtlas(minfo, logF_grid, par_list[i, :-lim], listpar, dims, isig) else: logF_list[i] = griddataBA(minfo, logF_grid, par_list[i, :-lim], listpar, dims) # convert to physical units logF_mod += np.log10(norma) logF_list += np.log10(norma) for j in range(len(logF_list)): chi2[j] = np.sum( (logF[keep] - logF_list[j][keep])**2 / (dlogF[keep])**2) # chib = chi2[np.argsort(chi2)[-30:]] / max(chi2) flux = 10.**logF dflux = dlogF * flux flux_mod = 10.**logF_mod flux_mod = pyasl.unred(lbd * 1e4, flux_mod, ebv=-1 * ebv, R_V=rv) # alphas = (1. - chi2 / max(chi2)) / 50. # Plot definitions bottom, left = 0.71, 0.48 width, height = 0.96 - left, 0.785 - bottom plt.axes([left, bottom, width, height]) # plot fit for i in range(len(par_list)): ebv_temp = np.copy(par_list[i][-lim2]) F_temp = pyasl.unred(lbd * 1e4, 10**logF_list[i], ebv=-1 * ebv_temp, R_V=rv) plt.plot(lbd, (flux - F_temp) / dflux, 'bs', alpha=0.2) # plt.plot(lbd, (flux - flux_mod) / dflux, 'bs', markersize=5, alpha=0.1) # plt.ylabel('$(\mathrm{F}-F_\mathrm{model})/\sigma$', fontsize=20) plt.ylabel('$(F-F_\mathrm{m})/\sigma$', fontsize=20) plt.xlabel('$\lambda\,\mathrm{[\mu m]}$', fontsize=20) # plt.ylim(-100, 100) plt.hlines(y=0, xmin=min(lbd), xmax=max(lbd), linestyles='--', color='black') plt.xlim(min(lbd), max(lbd)) if model == 'aara' or model == 'beatlas' or\ model == 'acol' or model == 'bcmi': plt.xscale('log') plt.tick_params(direction='in', length=6, width=2, colors='gray', which='both') plt.legend(loc='upper right') return
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import matplotlib import matplotlib.pylab as plt input_value = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] plt.plot(input_value, squares, linewidth=5) #设置图标标题,并给坐标轴加上标签 plt.title("Square Numbers", fontsize=24) plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) #设置刻度标记的大小 plt.tick_params(axis='both', labelsize=14) #plt.plot(squares) plt.show()
def recordingAndWriting(): # stream=p.open(format = pyaudio.paInt16, # channels = CHANNELS, # rate = RATE, # frames_per_buffer = CHUNK, # input = True) # frames = [] # print "start" # for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): # input = stream.read(CHUNK) # frames.append(input) # print "stop" # stream.stop_stream() # stream.close() # p.terminate() #wav書込 data = soundDetector.record_wrap() #print WAVE_OUTPUT_FILENAME #data = b''.join(frames) wf = wave.open(WAVE_OUTPUT_FILENAME, "wb") wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(pyaudio.paInt16)) wf.setframerate(RATE) wf.writeframes(data) wf.close() start = 0 data = frombuffer(data, dtype= "int16") / 32768.0 amplitudeSpectrum = data2fft(data) N = data.shape[0] freqList = np.fft.fftfreq(N, d=1.0/44100) subplot(311) # 3行1列のグラフの1番目の位置にプロット plot(range(start, start+N), data[start:start+N]) axis([start, start+N, -1.0, 1.0]) xlabel("time [sample]") ylabel("amplitude") fs = 44100 # 振幅スペクトルを描画 subplot(312) hogehoge = np.array(freqList) hagehage = np.array(amplitudeSpectrum) print hogehoge.shape, hagehage.shape plot(freqList, amplitudeSpectrum, marker= 'o', linestyle='-') axis([0, fs/2, 0, 50]) xlabel("frequency [Hz]") ylabel("amplitude spectrum") show() #outputの関数を呼ぶ ap = outmod.AudioPlayer() ap.setAudioFile(WAVE_OUTPUT_FILENAME) outmod.playLoop(ap) #画像生成 fs, data = read(WAVE_OUTPUT_FILENAME) cq_spec, freqs = cq_fft(data, fs) w, h = cq_spec.shape fig = pl.figure() fig.add_subplot(111) pl.imshow(abs(cq_spec).T, aspect = "auto", origin = "lower") pl.tick_params(labelbottom='off') pl.tick_params(labelleft='off') pl.savefig(IMAGE_OUTPUT_FILENAME, bbox_inches='tight') f = open(RAW_OUTPUT_FILENAME, 'w') pickle.dump(cq_spec, f) f.close() return IMAGE_OUTPUT_FILENAME
def plot_sfh(self, attr_str, ax=None, outfile=None, yscale='linear', plot_random_arrays_kw=None, errorbar_kw=None, twoplots=False): ''' plot the data from the sfh file. ''' plot_random_arrays_kw = plot_random_arrays_kw or {} # set up errorbar plot errorbar_kw = errorbar_kw or {} errorbar_default = {'linestyle': 'steps-mid', 'lw': 3, 'color': 'darkred'} errorbar_kw = dict(errorbar_default.items() + errorbar_kw.items()) # load the plotting values and their errors, this could be generalized # and passed ... val_arr = self.data.__getattribute__(attr_str) errm_arr = self.data.__getattribute__('%s_errm' % attr_str) errp_arr = self.data.__getattribute__('%s_errp' % attr_str) if 'sfr' in attr_str: ylab = '${\\rm SFR\ (10^3\ M_\odot/yr)}$' val_arr *= 1e3 errm_arr *= 1e3 errp_arr *= 1e3 plot_random_arrays_kw['moffset'] = 1e3 elif 'm' in attr_str: ylab = '${\\rm [M/H]}$' elif 'fe' in attr_str: ylab = '${\\rm [Fe/H]}$' # mask 0 values so there is a vertical line on the plot val_arr[val_arr==0] = 1e-15 errm_arr[errm_arr==0] = 1e-15 errp_arr[errp_arr==0] = 1e-15 if twoplots is True: fig, axs = plt.subplots(figsize=(8, 8), nrows=2, sharex=True) else: fig, ax = plt.subplots(figsize=(8, 5)) axs = [ax] for ax in axs: if not 'm' in attr_str: ax.errorbar(self.data.lagei, val_arr, [errm_arr, errp_arr], zorder=100, **errorbar_kw) if len(plot_random_arrays_kw) > 0: # if loading the random arrays from files, need to give the # attribute to load. if plot_random_arrays_kw['from_files'] is True: plot_random_arrays_kw['attr_str'] = attr_str self.plot_random_arrays(ax=ax, **plot_random_arrays_kw) ax.set_ylabel(ylab, fontsize=20) ax.set_xlim(7.9, 10.13) target = self.name.split('.')[0].upper().replace('-', '\!-\!') if twoplots is True: ax = axs[1] # lower plot limit doesn't need to be 1e-15... axs[0].set_ylim(1e-7, axs[0].get_ylim()[1]) axs[0].set_yscale('log') fig.subplots_adjust(hspace=0.09) else: fig.subplots_adjust(bottom=0.15) ax.annotate('$%s$' % target, (0.02, 0.97), va='top', xycoords='axes fraction', fontsize=16) ax.set_xlabel('$\log {\\rm Age (yr)}$', fontsize=20) plt.tick_params(labelsize=16) if outfile is not None: plt.savefig(outfile, dpi=150) return ax
#def getIntensitiesMap(masked_image_file, skeletons_file, intensities_file, roi_size = 128): with tables.File(masked_image_file, 'r') as mask_fid, \ tables.File(skeletons_file, 'r') as ske_file_id: for worm_index, row_range in rows_indexes.iterrows(): worm_data = WormClass(skeletons_file, worm_index, \ rows_range = (row_range['min'],row_range['max'])) angles_head, angles_tail = calculateHeadTailAng(worm_data.skeleton, 5, ~np.isnan(worm_data.skeleton[:,0,0])) ts = pd.DataFrame({'head_angle':angles_head, 'tail_angle':angles_tail}) #%% roll_std = pd.rolling_std(ts, window = window_std, min_periods = window_std-max_gap_allowed); plt.figure() plt.tick_params(labelsize=15) plt.plot(ts['head_angle'], 'g', label='head', linewidth = 1.5) plt.plot(ts['tail_angle'], 'm', label='tail', linewidth = 1.5) plt.xlim((0, 4500)) plt.xlabel('Time Frame', fontsize=20) plt.ylabel('Angle (Rad)', fontsize=20) plt.legend() plt.savefig('head_tail.png', dpi = 300) #%% plt.figure() plt.tick_params(labelsize=15) plt.axis(fontsize=20) plt.plot(roll_std['head_angle'], 'g', linewidth = 1.5) plt.plot(roll_std['tail_angle'], 'm', linewidth = 1.5) plt.xlim((0, 4500))