def print_latex(): for i in range(1,7):Respostas[i] = sympy.nsimplify(Respostas[i].evalf(prec), rational = True,tolerance = 0.05) # 0- Raizes; 1- Forma Natural da respsota; 2- Resposta Natural; # 3- Resposta Particular; 4- Resposta Transitoria; 5- Respsota Forcada # 6- Resposta Completa # 7-Sinal de entrada x(t) ### eqDiferencialEntradaLatex = latex(eq) ##Perfumaria dif = 0.9 -0.77 xdif = -0.15 font = {'family' : 'Sans', 'weight' : 'normal', 'size' : 18} plt.rc('font', **font) ##Obtendo as respostas em Latex RespostasEmLatex = [0]*(len(Respostas)) raizEmLatex = [0]*(len(Respostas[0])) str_raizLatex ="" for i in range(len(Respostas[0])): raizEmLatex[i] = '$'+str(latex(Respostas[0][i])) +'$' for i in range(len(raizEmLatex)): rn = "r"+str(i+1)+" = " rn = '$'+str(latex(rn)) +'$' str_raizLatex = str_raizLatex+"\t"+rn+raizEmLatex[i] ##print len(RespostasEmLatex) for i in range(len(Respostas)): RespostasEmLatex[i] = '$'+str(latex(Respostas[i])) +'$' #print RespostasEmLatex xTLatex = '$' + latex(xT) +'$' ###Preparando para imprimir log_figure = plt.figure("Representacao",facecolor='white') ax1 = plt.axes(frameon = False) ax1.get_xaxis().tick_bottom() ax1.get_xaxis().set_visible(False) ax1.axes.get_yaxis().set_visible(False) for i in range(0,8,1): plt.axhline(0.86-dif*i,xmin = -5,xmax = 5, color = 'black',lw =0.2, linestyle = ':') #log_figure.figure("Forma_Representativa:") plt.title("Eq dif: 0="+ur'$'+eqDiferencialEntradaLatex+'$', loc = 'left',fontsize = 15) plt.text(xdif,0.89,'Forma Natural:'+ur''+RespostasEmLatex[1]) plt.text(xdif,0.9-dif,'yn(t) = '+ur''+RespostasEmLatex[2]) plt.text(xdif,0.9-2*dif,'ypar(t) = '+ur''+RespostasEmLatex[3]) plt.text(xdif,0.9-3*dif,'ytran(t) = '+ur''+RespostasEmLatex[4]) plt.text(xdif,0.9-4*dif,'yfor(t) = '+ur''+RespostasEmLatex[5]) plt.text(xdif,0.9-5*dif,'yc(t) = '+ur''+RespostasEmLatex[6]) plt.text(xdif,0.9-6*dif,'x(t) = '+ur''+xTLatex) plt.text(xdif,0.9-7*dif,'Raiz(es): '+ur''+str_raizLatex) ##log_figure.set_size_inches(19.2,10.8) #log_figure.show() plt.show() return log_figure
def disc_norm(): x = np.linspace(-3,3,100) y = st.norm.pdf(x,0,1) fig, ax = plt.subplots() fig.canvas.draw() ax.plot(x,y) fill1_x = np.linspace(-2,-1.5,100) fill1_y = st.norm.pdf(fill1_x,0,1) fill2_x = np.linspace(-1.5,-1,100) fill2_y = st.norm.pdf(fill2_x,0,1) ax.fill_between(fill1_x,0,fill1_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75) ax.fill_between(fill2_x,0,fill2_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75) for label in ax.get_yticklabels(): label.set_visible(False) for tick in ax.get_xticklines(): tick.set_visible(False) for tick in ax.get_yticklines(): tick.set_visible(False) plt.rc("font", size = 16) plt.xticks([-2,-1.5,-1]) labels = [item.get_text() for item in ax.get_xticklabels()] labels[0] = r"$v_k$" labels[1] = r"$\varepsilon_k$" labels[2] = r"$v_{k+1}$" ax.set_xticklabels(labels) plt.ylim([0, .45]) plt.savefig('discnorm.pdf') plt.clf()
def png(self, start_timestamp, end_timestamp): self.load(start_timestamp, end_timestamp) plt.figure(figsize=(10, 7.52)) plt.rc("axes", labelsize=12, titlesize=14) plt.rc("font", size=10) plt.rc("legend", fontsize=7) plt.rc("xtick", labelsize=8) plt.rc("ytick", labelsize=8) plt.axes([0.08, 0.08, 1 - 0.27, 1 - 0.15]) for plot in self.plots: plt.plot(self.timestamps, self.plots[plot], self.series_fmt(plot), label=self.series_label(plot)) plt.axis("tight") plt.gca().xaxis.set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, pos=None: time.strftime("%H:%M\n%b %d", time.localtime(x))) ) plt.gca().yaxis.set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, pos=None: locale.format("%.*f", (0, x), True)) ) plt.grid(True) plt.legend(loc=(1.003, 0)) plt.xlabel("Time/Date") plt.title( self.description() + "\n%s to %s" % ( time.strftime("%H:%M %d-%b-%Y", time.localtime(start_timestamp)), time.strftime("%H:%M %d-%b-%Y", time.localtime(end_timestamp)), ) ) output_buffer = StringIO.StringIO() plt.savefig(output_buffer, format="png") return output_buffer.getvalue()
def plot(title, dates, lines, labels, count, name, wdir): N = len(dates) start = N - count date_idx = range(count) def format_date(x, pos=None): idx = start + int(x) if idx >= N: idx = N - 1 return dates[idx].strftime('%m-%d') plt.rcParams.update({'font.size': 9}) plt.rc('legend', **{'fontsize':8}) fig = plt.figure() # ax = fig.add_subplot(111) ax = fig.add_axes([0.075, 0.125, 0.68, 0.765]) handles = [] for i in range(len(lines)): handle = ax.plot(date_idx, lines[i][start:], label=labels[i]) handles.append(handle) ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) fig.autofmt_xdate() fig.set_size_inches(4.25, 2.15) fig.legend(handles, labels, 'upper right') plt.title(title) filename = wdir + '\\' + name + '.png' # plt.show() plt.savefig(filename) return (name, filename)
def plot(filename): import os from matplotlib.pyplot import clf, tricontour, tricontourf, \ gca, savefig, rc, minorticks_on if not os.path.exists(filename): return -1 rc('text', usetex=True) clf() x, y, tri, ux, uy = load_velocity(filename) tricontourf(x, y, tri, ux, 16) tricontour(x, y, tri, ux, 16, linestyles='-', colors='black', linewidths=0.5) minorticks_on() gca().set_aspect('equal') gca().tick_params(direction='out', which='both') gca().set_xticklabels([]) gca().set_yticklabels([]) name, _ = os.path.splitext(filename) name = os.path.basename(name) savefig('{0}.png'.format(name), dpi=300, bbox_inches='tight') savefig('{0}.pdf'.format(name), bbox_inches='tight')
def hist(nndist, **kwds): if 'output' in kwds: import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt # handle formatting keywords linewidth = kwds.get('linewidth', 3) #plt.rc('text', usetex=True) plt.rc('font', family='serif') n, bins, patches = plt.hist(nndist, normed=True, bins=100) width = bins[1] - bins[0] ax1 = plt.gca() ax2 = plt.twinx() ax2.plot(bins[:-1], width*np.cumsum(n), 'r-', linewidth=linewidth) ax2.set_ylim(top=1.0) tics = ax1.get_yticks(); ax1.set_yticks(tics[1:]) tics = ax2.get_yticks(); ax2.set_yticks(tics[1:]) ax1.set_xlabel(r"d ($\mu$m)") ax1.set_ylabel(r"PDF") ax2.set_ylabel(r"CDF", color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') # check scalar descriptors median_dist = np.median(nndist) ax1.axvline(median_dist, color='gray', linewidth=linewidth) # handle keywords if 'title' in kwds: plt.title(kwds['title']) if 'output' in kwds: plt.draw() plt.savefig(kwds['output']) else: plt.show()
def plot_all(): font = {'family': 'serif', 'weight': 'normal', 'size': 12, } plt.rc('font', **font) data = DataReader('dyn_spin.txt') ts = data['time'] fig = plt.figure(figsize=(5, 4)) mx = data['m_x'] my = data['m_y'] mz = data['m_z'] plt.plot(ts, mx, '-', label='mx', color='b') plt.plot(ts, my, '-', label='my', color='g') plt.plot(ts[::6], mz[::6],'.-', label='mz', color='r') plt.legend(bbox_to_anchor=[0.8, 0.8], shadow=True, frameon=True) #plt.xlim([0, 1.01]) plt.legend() plt.xlabel('Time') plt.ylabel('m') plt.tight_layout() fig.savefig('m_ts.pdf')
def bias_KSB_weight(Args, gal_hlr): """Make plots to analyze CG bias with weight function""" mcg_w_ksb, ccg_w_ksb = [],[] weights=np.linspace(0.5,2, 15) rt_g=[[0.005,0.005],[0.01,0.01]] gtrue=np.array(rt_g) for w in weights: input_args = Args input_args.shear_est='KSB' input_args.sig_w = w*gal_hlr input_args.rt_g = rt_g gcgw,gnocgw=cg.calc_cg(input_args) fit_fin = np.polyfit(gtrue.T[0],gcgw.T-gnocgw.T,1) mcg_w_ksb.append(fit_fin[0]) ccg_w_ksb.append(fit_fin[1]) k=0 plt.rc('legend',**{'fontsize':16}) plt.figure(figsize=[12,8]) #plt.subplots_adjust(hspace=0.4) #plt.subplots_adjust(wspace = 0.4) #plt.subplot(221) if Args.telescope is 'Euclid': plt.plot(weights,-np.array(mcg_w_ksb).T[k],label='KSB',linewidth=2.5) plt.ylabel(r'-$\rm m_{CG}$', size=22) else: plt.plot(weights,np.array(mcg_w_ksb).T[k],label='KSB',linewidth=2.5) plt.ylabel(r'$\rm m_{CG}$', size=22) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.xlabel(r'weight function size/galaxy size',size=20) plt.title(r'Dependence of $\rm m_{CG}$ '+'on weight function size for {0}'.format(Args.telescope), size=22) plt.xticks(fontsize = 16) plt.yticks(fontsize = 16)
def boxplotThem(dataToPlot,title): means = [np.mean(item) for item in dataToPlot] fig = plt.figure(1, figsize=(9,6)) ax = fig.add_subplot(111) plt.rc('text', usetex=True) plt.rc('font', family='serif') for i in range(25): print('length ',str(i+1)) for item in dataToPlot[i]: ax.scatter(i+1,item) ax.plot(list(range(1,26)),means,linewidth=4,color='r') ax.set_xticks([1,5,10,15,20,25]) ax.set_xticklabels([r"$1",r"$5$",r"$10$",r"$15$",r"$20$",r"$25$"],fontsize = 25) ax.set_yscale('log') ax.set_yticks([0.00000001,0.000001,0.0001,0.01,1]) ax.xaxis.set_tick_params(width=1.5) ax.yaxis.set_tick_params(width=1.5) ax.set_yticklabels([r"$10^{-8}$",r"$10^{-6}$",r"$10^{-4}$",r"$10^{-2}$",r"$1$"],fontsize = 25) ax.get_yaxis().get_major_formatter().labelOnlyBase = False ax.set_ylabel('relative population',fontsize = 30) ax.set_xlabel(r'length',fontsize = 30) ax.set_xlim(0,26) ax.set_ylim(0.00000005) plt.suptitle(title,fontsize=25) plt.savefig(r.outputDir+'distr.png')
def setup_colors(): pyplot.rc('axes', color_cycle=['#ff0000','#00ff00','#0000ff', '#ffff00','#ff00ff','#00ffff', '#000000','#ff8000','#0080ff', '#ff0080','#80ff00','#8000ff', '#00ff80','#ff8080','#80ff80', '#8080ff'])
def dim_sensitivity_plot(x, Y, fname, show_legend=True): plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.figure(figsize=(3, 3)) plt.xlabel('$d$', size=FONTSIZE) plt.ylabel('ROC AUC', size=FONTSIZE) plt.set_cmap('Set2') lines = [] for i, label in enumerate(KEYS): line_data = Y.get(label) if line_data is None: continue line, = plt.plot(x, line_data, label=label, marker=MARKERS[i], markersize=0.5 * FONTSIZE, color=COLORS[i]) lines.append(line) if show_legend: plt.legend(handles=lines) plt.legend(loc='lower right') plt.xscale('log', basex=2) plt.xticks(x, [str(y) for y in x], size=FONTSIZE) plt.yticks(size=FONTSIZE) plt.tight_layout() plt.savefig(fname)
def test_tilde_in_tempfilename(): # Tilde ~ in the tempdir path (e.g. TMPDIR, TMP oder TEMP on windows # when the username is very long and windows uses a short name) breaks # latex before https://github.com/matplotlib/matplotlib/pull/5928 import tempfile import shutil import os import os.path tempdir = None old_tempdir = tempfile.tempdir try: # change the path for new tempdirs, which is used # internally by the ps backend to write a file tempdir = tempfile.mkdtemp() base_tempdir = os.path.join(tempdir, "short~1") os.makedirs(base_tempdir) tempfile.tempdir = base_tempdir # usetex results in the latex call, which does not like the ~ plt.rc('text', usetex=True) plt.plot([1, 2, 3, 4]) plt.xlabel(r'\textbf{time} (s)') #matplotlib.verbose.set_level("debug") output_eps = os.path.join(base_tempdir, 'tex_demo.eps') # use the PS backend to write the file... plt.savefig(output_eps, format="ps") finally: tempfile.tempdir = old_tempdir if tempdir: try: shutil.rmtree(tempdir) except Exception as e: # do not break if this is not removeable... print(e)
def PlotData(Stock,buyselldata): plt.rc('axes', grid=True) plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5) textsize = 9 left, width = 0.1, 0.8 rect1 = [left, 0.1, width, 0.9] fig = plt.figure(facecolor='white') axescolor = '#f6f6f6' # the axies background color ax1 = fig.add_axes(rect1, axisbg=axescolor) #left, bottom, width, height ### plot the relative strength indicator prices = Stock.close fillcolor = 'darkgoldenrod' plt.plot(Stock.date, prices, color=fillcolor) for i in buyselldata[0]: plt.plot(Stock.date[i],prices[i],'bo') for i in buyselldata[1]: plt.plot(Stock.date[i],prices[i],'rx') plt.show()
def visualize_data(mnist): plt.rc("image",cmap="binary") plt.subplot(10,10,1) for i in range(100): plt.subplot(10,10,i) idx=np.random.randint(len(mnist.data)) plt.imshow(mnist.data[idx].reshape(28,28))
def plot(self, debug = False): """plot figures for population, nuisance parameters""" # first figure out what scheme is used self.list_scheme() # next get MABR sampling done self.MBAR_analysis() # load in precomputed P and dP from MBAR analysis pops0, pops1 = self.P_dP[:,0], self.P_dP[:,self.K-1] dpops0, dpops1 = self.P_dP[:,self.K], self.P_dP[:,2*self.K-1] t0 = self.traj[0] t1 = self.traj[self.K-1] # Figure Plot SETTINGS label_fontsize = 12 legend_fontsize = 10 fontfamily={'family':'sans-serif','sans-serif':['Arial']} plt.rc('font', **fontfamily) # determine number of row and column if (len(self.scheme)+1)%2 != 0: c,r = 2, (len(self.scheme)+2)/2 else: c,r = 2, (len(self.scheme)+1)/2 plt.figure( figsize=(4*c,5*r) ) # Make a subplot in the upper left plt.subplot(r,c,1) plt.errorbar( pops0, pops1, xerr=dpops0, yerr=dpops1, fmt='k.') plt.hold(True) plt.plot([1e-6, 1], [1e-6, 1], color='k', linestyle='-', linewidth=2) plt.xlim(1e-6, 1.) plt.ylim(1e-6, 1.) plt.xlabel('$p_i$ (exp)', fontsize=label_fontsize) plt.ylabel('$p_i$ (sim+exp)', fontsize=label_fontsize) plt.xscale('log') plt.yscale('log') # label key states plt.hold(True) for i in range(len(pops1)): if (i==0) or (pops1[i] > 0.05): plt.text( pops0[i], pops1[i], str(i), color='g' ) for k in range(len(self.scheme)): plt.subplot(r,c,k+2) plt.step(t0['allowed_'+self.scheme[k]], t0['sampled_'+self.scheme[k]], 'b-') plt.hold(True) plt.xlim(0,5) plt.step(t1['allowed_'+self.scheme[k]], t1['sampled_'+self.scheme[k]], 'r-') plt.legend(['exp', 'sim+exp'], fontsize=legend_fontsize) if self.scheme[k].find('cs') == -1: plt.xlabel("$\%s$"%self.scheme[k], fontsize=label_fontsize) plt.ylabel("$P(\%s)$"%self.scheme[k], fontsize=label_fontsize) plt.yticks([]) else: plt.xlabel("$\sigma_{%s}$"%self.scheme[k][6:],fontsize=label_fontsize) plt.ylabel("$P(\sigma_{%s})$"%self.scheme[k][6:],fontsize=label_fontsize) plt.yticks([]) plt.tight_layout() plt.savefig(self.picfile)
def plot_objectivefunctiontraces(results,evaluation,algorithms,filename='Like_trace'): import matplotlib.pyplot as plt from matplotlib import colors cnames=list(colors.cnames) font = {'family' : 'calibri', 'weight' : 'normal', 'size' : 20} plt.rc('font', **font) fig=plt.figure(figsize=(16,3)) xticks=[5000,15000] for i in range(len(results)): ax = plt.subplot(1,len(results),i+1) likes=calc_like(results[i],evaluation) ax.plot(likes,'b-') ax.set_ylim(0,25) ax.set_xlim(0,len(results[0])) ax.set_xlabel(algorithms[i]) ax.xaxis.set_ticks(xticks) if i==0: ax.set_ylabel('RMSE') ax.yaxis.set_ticks([0,10,20]) else: ax.yaxis.set_ticks([]) plt.tight_layout() fig.savefig(str(filename)+'.png')
def plotcurve(xax,f1,f2,ct): fig, axes = plt.subplots(nrows=4, ncols=1, sharex=True) plt.minorticks_on() fig.subplots_adjust(hspace = 0.001) plt.rc('font', family='serif',serif='Times') y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) axes[0].plot(xax,f1[0],'D-',c='k',mec='b',fillstyle='none') axes[0].plot(xax,f2[0],'o-',c='g',mec='k',fillstyle='none') axes[0].set_ylabel(r'$raw$ $RMS$',fontsize=13) axes[0].yaxis.set_major_formatter(y_formatter) axes[0].yaxis.set_major_locator(MaxNLocator(prune='both',nbins=5)) axes[1].plot(xax,f1[1],'D-',c='k',mec='b',fillstyle='none') axes[1].plot(xax,f2[1],'o-',c='g',mec='k',fillstyle='none') axes[1].set_ylabel(r'$frames$ $RMS$',fontsize=13) axes[1].yaxis.set_major_formatter(y_formatter) axes[1].yaxis.set_major_locator(MaxNLocator(prune='both',nbins=5)) axes[2].plot(xax,f1[2],'D-',c='k',mec='b',fillstyle='none') axes[2].plot(xax,f2[2],'o-',c='g',mec='k',fillstyle='none') axes[2].set_ylabel(r'$\sigma-clipped$',fontsize=13) axes[2].yaxis.set_major_formatter(y_formatter) axes[2].yaxis.set_major_locator(MaxNLocator(prune='both',nbins=5)) axes[3].plot(xax,f1[3],'D-',c='k',mec='b',fillstyle='none',label='Hard') axes[3].plot(xax,f2[3],'o-',c='g',mec='k',fillstyle='none',label='Soft') axes[3].set_ylabel(r'$\sigma$ $clipped$ $RMS$',fontsize=13) axes[3].set_xlabel(r'$aperture$ $(pixels)$',fontsize=13) axes[3].yaxis.set_major_formatter(y_formatter) axes[3].yaxis.set_major_locator(MaxNLocator(prune='both',nbins=5)) axes[3].legend(numpoints=1) plt.savefig('paneltest/'+str(ct)+'updchanges.png',bbox_inches='tight',dpi=200)
def hw8_plot_NPT_instant_msd(): T_labels = ['0.50', '1.00', '2.00'] T = [0.5, 1.0, 2.0] N = ['32', '108', '256'] P = ['1.0', '10.0', '20.0'] pyplot.rc('legend',**{'fontsize':10}) # Plots NVT energies i = 0 for p in P: for n in N: i += 1 ax = pyplot.subplot(620 + i) for t in T_labels: row = hw8_get_data(n, 'NPT', t, 1, p) pyplot.setp(ax.get_xticklabels(), fontsize=8) pyplot.setp(ax.get_yticklabels(), fontsize=8) pyplot.plot(row[:,c_step_number], row[:,c_msd], label = 'T = ' + t, linestyle = '--') pyplot.xlabel('Step', fontsize=10) pyplot.ylabel('MSD', fontsize=10) pyplot.legend(loc="upper right") pyplot.title('NPT, P = ' + p +', N = ' + n + ', Density = 0.9', fontsize=10) pyplot.show()
def StDistributionPlot(Stdistribution): ''' Given a dict cointaning azi and dist for each stations it makes a plot of the distribution ''' fig = plt.figure(figsize=(10,10)) plt.rc('grid', color='#316931', linewidth=1, linestyle='-') ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c') for trid, val in Stdistribution.iteritems(): idsplit = trid.split(".") stname = idsplit[1] ax.plot([val['azi']],[val['dist']],'o', ms=15) ax.annotate(stname,xytext=(val['azi'], val['dist']), xy = (val['azi'], val['dist'])) ax.set_rgrids(ax.get_yticks(), angle=135) ticks = [str(tick) + r'$^o$' for tick in ax.get_yticks()] print ticks ax.set_yticklabels(ticks) ax.set_theta_zero_location("N") ax.set_theta_direction(1) ax.set_thetagrids([0, 90, 180, 270], labels = ['N', 'E', 'S', 'W' ] )
def make_accuracy_plot(): from numpy import linspace, mean from math import pi from matplotlib import pyplot as pl pl.rc('text', usetex=True) pl.rc('font', family='serif') pl.axvline(x=1,color='k') pl.xlabel(r'$$\lambda$$',fontsize=16) pl.ylabel(r'$$\epsilon$$',fontsize=16) print "Testing M=0" it_list = list() #We test for zero revolutions err,it,la,x,T = test_standard(M=100000,gooding=False, house=True,tau=False,iter_max=15,eps=1e-5, rnd_seed=4562,N=0) it_list.append(mean(it)) pl.semilogy(la,err,'k.') #We test for multiple revolutions for rev in range(50): print "Testing M=" + str(rev) err,it,la,x,T = test_standard(M=10000,gooding=False, house=True,tau=False,iter_max=15,eps=1e-8, rnd_seed=4562+rev+1,N=rev+1) pl.semilogy(la,err,'k.') it_list.append(mean(it)) pl.figure() pl.plot(it_list)
def plotSeqsAvesLen(self,categories): (autox,autoy,foldx,foldy,regx,regy) = categories plt.gcf().subplots_adjust(bottom=0.15) plt.gcf().subplots_adjust(left=0.15) fig = plt.figure(1, figsize=(9,6)) ax = fig.add_subplot(111) plt.rc('text', usetex=True) plt.rc('font', family='serif') ax.scatter(regx,regy,color='0.4') ax.scatter(foldx,foldy,color='b') ax.scatter(autox,autoy,color='r') ax.set_yscale('log') ax.set_xticks([1,5,10,15,20,25]) ax.set_xticklabels([r"$1",r"$5$",r"$10$",r"$15$",r"$20$",r"$25$"],fontsize = 25) ax.set_yticks([0.000001,0.0001,0.01,1,100]) ax.set_yticklabels( [r"$10^{-6}$",r"$10^{-4}$",r"$10^{-2}$",r"$1$",r"$10^2$"], fontsize = 25) ax.get_yaxis().get_major_formatter().labelOnlyBase = False ax.xaxis.set_tick_params(width=1.5) ax.yaxis.set_tick_params(width=1.5) ax.set_ylabel('population',fontsize = 30) ax.set_xlabel(r'length',fontsize = 30) ax.set_xlim(0,26) ax.set_ylim(0.000001) plt.savefig(os.path.join( self.outputDir,'scatter'+str(self.trajectory[2])+'.pdf')) plt.savefig(os.path.join( self.outputDir,'scatter'+str(self.trajectory[2])+'.png'))
def make_xi_plot(): from numpy import linspace from matplotlib import pyplot as pl pl.rc('text', usetex=True) pl.rc('font', family='serif') lamdas = [-1,-0.9,-0.7,0,0.7,0.9,1] for lam in lamdas: plotx(lam,0,linestyle='k',minval=-0.9,maxval=10.0,logplot=True) plotx(lam,1,linestyle='k--',logplot=True) plotx(lam,2,logplot=True) plotx(lam,3,linestyle='k--',logplot=True) pl.vlines(x=1,ymin=-2,ymax=-0.076,color='k') pl.xlabel(r'$$\xi$$',fontsize=16) pl.ylabel(r'$$\tau$$',fontsize=16) pl.text(0.0, 0, r'$$M=0$$', bbox=dict(facecolor='white', alpha=1)) pl.text(0.0, 1.4, r'$$M=1$$', bbox=dict(facecolor='white', alpha=1)) pl.text(0, 2.48, r'$$M=2$$', bbox=dict(facecolor='white', alpha=1)) pl.text(1.3, -1.5, r'hyperbolic') pl.text(0.3, -1.5, r'elliptic') pl.annotate(r'$$\lambda = 1$$', xy=(-0.29, -0.19), xytext=(-1, -1), arrowprops=dict(facecolor='black', shrink=0.15, width=1,headwidth=5), ) pl.annotate(r'$$\lambda = -1$$', xy=(0.7, 0.4), xytext=(0.8,0.8), arrowprops=dict(facecolor='black', shrink=0.15, width=1,headwidth=5), ) pl.xlim((-2,2)) pl.ylim((-2,3))
def make_rainbow(a=0.75, b=0.2, name='custom_rainbow', register=False): """ Use a=0.7, b=0.2 for a darker end. when 0.5<=a<=1.5, should have b >= (a-0.5)/2 or 0 <= b <= (a-1)/3 when 0<=a<=0.5, should have b >= (0.5-a)/2 or 0<= b<= -a/3 to assert the monoique To show the parameter dependencies interactively in notebook ``` %matplotlib inline from ipywidgets import interact def func(a=0.75, b=0.2): cmap = gene_rainbow(a=a, b=b) show_cmap(cmap) interact(func, a=(0, 1, 0.05), b=(0.1, 0.5, 0.05)) ``` """ def gfunc(a, b, c=1): def func(x): return c * np.exp(-0.5 * (x - a)**2 / b**2) return func cdict = {"red": gfunc(a, b), "green": gfunc(0.5, b), "blue": gfunc(1 - a, b) } cmap = mpl.colors.LinearSegmentedColormap(name, cdict) if register: plt.register_cmap(cmap=cmap) plt.rc('image', cmap=cmap.name) return cmap
def prepare_figure(obj_area): # create new figure #fig = Figure() # old version, does not work for the stream plot ## Turn interactive plotting off #plt.ioff() fig = plt.figure() # needs a DISPLAY environment variable (simulated here with mpl.use('Agg')) # define size of image nx = obj_area.x_size ny = obj_area.y_size # canvas figure canvas = FigureCanvas(fig) # get dots per inch of the screen DPI = fig.get_dpi() # print "DPI", DPI fig.set_size_inches(nx/float(DPI),ny/float(DPI)) # set fonts to bold plt.rc('font', weight='bold') # get axis object ax = fig.add_subplot(111, aspect='equal') ## eliminates margins totally fig.subplots_adjust(left=0.0,right=1.0,bottom=0.0,top=1.0, wspace=0, hspace=0) # set limits of the axis ax.set_xlim(0, nx) ax.set_ylim(0, ny) # set transparent backgroud fig.patch.set_alpha(0.0) # transparent outside of diagram ax.set_axis_bgcolor([1,0,0,0]) # transparent color inside diagram return fig, ax
def plot(results, total_a, total_b, label_a, label_b, outputFile=None): all_rules = sorted(results, key=lambda v: (-len(v['item']), round(abs(v['count_a'] / total_a - v['count_b'] / total_b), 2), round(v['count_a'] / total_a, 2))) values_a = [100 * rule['count_a'] / total_a for rule in all_rules] values_b = [100 * rule['count_b'] / total_b for rule in all_rules] plt.rc('figure', autolayout=True) plt.rc('font', size=22) fig, ax = plt.subplots(figsize=(24, 18)) index = range(len(all_rules)) bar_width = 0.35 if label_a.startswith('_'): label_a = ' ' + label_a if label_b.startswith('_'): label_b = ' ' + label_b bar_a = plt.barh(index, values_a, bar_width, color='b', label=label_a) bar_b = plt.barh([i + bar_width for i in index], values_b, bar_width, color='r', label=label_b) plt.xlabel('Support') plt.ylabel('Rule') plt.title('Most interesting deviations') plt.yticks([i + bar_width for i in index], [rule_to_str(rule['item']) for rule in all_rules]) if len(all_rules) > 0: plt.legend(handles=[bar_b, bar_a], loc='best') if outputFile is not None: plt.savefig(outputFile) else: plt.show() plt.close(fig)
def printEnrichment(controlVsTestTupleList, proteinGroupsDataFrame, go_to_SGDID,sgdidList): f, axarr = plt.subplots(4, 2) f.subplots_adjust(hspace = 0.75) i = 0 j = 0 font ={'family':'normal', 'weight':'bold', 'size':8} plt.rc('font', **font) for (control, test) in controlVsTestTupleList: e1, n1 = calculate_enrichment(test, proteinGroupsDataFrame, go_to_SGDID,sgdidList) e0, n0 = calculate_enrichment(control, proteinGroupsDataFrame, go_to_SGDID,sgdidList) e0list, e1list, egoidlist, emaxlist = checkGoLengths(e0, e1) n0list, n1list, ngoidlist, nmaxlist = checkGoLengths(n0, n1) maxlist = [emaxlist[0], emaxlist[1], nmaxlist[0], nmaxlist[1]] axarr[i, j].plot(e0list, e1list, 'b.') axarr[i, j].plot(n0list, n1list, 'r.') axarr[i, j].set_title(control +'vs'+ test, fontsize=8) axarr[i, j].set_xlabel('control') axarr[i, j].set_ylabel('test') axarr[i, j].set_xlim([0, max(maxlist)]) axarr[i, j].set_ylim([0, max(maxlist)]) """index = 0 #to add all go ids to plot for xy in zip(e0list, e1list): axarr[i, j].annotate('%s' % egoidlist[index], xy=xy, textcoords='data') index+=1""" if j == 1: i+=1 j=0 else: j+=1 plt.show()
def plot_bars(groups, group_labels, legends, ylabel, yscale=None): N = len(group_labels) ind = np.arange(N) # the x locations for the groups width = 0.1 # the width of the bars plt.rc('xtick', labelsize=12) plt.rc('ytick', labelsize=12) fig = plt.figure(figsize=(14,7), dpi=300) ax = fig.add_subplot(111) colors = ['b', 'r', 'y', 'g', 'm'] rects = [] i = 0 for group in groups: rects.append(ax.bar(ind + ((i + 3) * 1.0 * width), group, width, bottom=10**-3, color=colors[i])) i += 1 ax.set_xticks(ind+0.5+width) ax.set_xticklabels( group_labels ) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.95, box.height]) ax.legend(rects, legends, loc='center left', bbox_to_anchor=(1, 0.5), prop={'size':14}) if yscale != None: plt.yscale(yscale) plt.ylabel(ylabel, fontsize=14) return plt
def make_x_plot(): from numpy import linspace from matplotlib import pyplot as pl pl.rc('text', usetex=True) pl.rc('font', family='serif') lamdas = [-1,-0.9,-0.7,0,0.7,0.9,1] for lam in lamdas: plotx(lam,0) plotx(lam,1,linestyle='k--') plotx(lam,2) plotx(lam,3,linestyle='k--') pl.axvline(x=1,color='k') pl.xlabel(r'$$x$$',fontsize=16) pl.ylabel(r'$$T$$',fontsize=16) pl.text(0.0, 1.5, r'$$M=0$$', bbox=dict(facecolor='white', alpha=1)) pl.text(0.0, 4.7, r'$$M=1$$', bbox=dict(facecolor='white', alpha=1)) pl.text(0.0, 8.0, r'$$M=2$$', bbox=dict(facecolor='white', alpha=1)) pl.text(0.5, 4, r'hyperbolic') pl.text(1.2, 4, r'elliptic') pl.annotate(r'$$\lambda = 1$$', xy=(-0.25, 1.1), xytext=(-0.8, 0.2), arrowprops=dict(facecolor='black', shrink=0.15, width=1,headwidth=5), ) pl.annotate(r'$$\lambda = -1$$', xy=(0.5, 2.0), xytext=(0.7, 3.0), arrowprops=dict(facecolor='black', shrink=0.15, width=1,headwidth=5), )
def features_pca_classified(fscaled, labels_true, labels_predict, axes=None, algorithm="pca"): if algorithm == 'pca': pc = PCA(n_components=2) fscaled_trans = pc.fit(fscaled).transform(fscaled) elif algorithm == "tsne": fscaled_trans = TSNE(n_components=2).fit_transform(fscaled) else: raise AlgorithmUnrecognizedException("Not recognizing method of "+ "dimensionality reduction.") sns.set_style("whitegrid") plt.rc("font", size=24, family="serif", serif="Computer Sans") plt.rc("axes", titlesize=20, labelsize=20) plt.rc("text", usetex=True) plt.rc('xtick', labelsize=20) plt.rc('ytick', labelsize=20) # make a Figure object if axes is None: fig, axes = plt.subplots(1,2,figsize=(16,6), sharey=True) ax1, ax2 = axes[0], axes[1] ax1 = plotting.scatter(fscaled_trans, labels_true, ax=ax1) # second panel: physical labels: ax2 = plotting.scatter(fscaled_trans, labels_predict, ax=ax2) plt.tight_layout() return ax1, ax2
def make_starter_plot(): from numpy import linspace from math import pi from matplotlib import pyplot as pl pl.rc('text', usetex=True) pl.rc('font', family='serif') pl.axvline(x=1,color='k') pl.xlabel(r'$$x$$',fontsize=16) pl.ylabel(r'$$T$$',fontsize=16) pl.text(0.5, 4, r'hyperbolic') pl.text(1.2, 4, r'elliptic') plot_x_curves([-1,-0.85,0.85,1],N=0,logplot=False,maxval=10,minval=-0.9) T0s = [pi,pi/2,1.1] for T0 in T0s: T =linspace(T0,10*pi) pl.plot((T0/T)**(2.0/3.0)-1.0,T,':k') T =linspace(0.1,T0) pl.plot((T0/T)**(1.0)-1.0,T,':k') pl.plot([],'k-',label="tof curves [-1,-0.85,0.85,1]") pl.plot([],'k:',label="initial guesses") pl.legend() pl.annotate(r'$$\lambda \le -0.85$$', xy=(-0.4, 7.5), xytext=(-0.1, 8), arrowprops=dict(facecolor='black', shrink=0.15, width=1,headwidth=5), ) pl.annotate(r'$$\lambda \ge 0.85$$', xy=(-0.33, 2.1), xytext=(-0.9, 1.09), arrowprops=dict(facecolor='black', shrink=0.15, width=1,headwidth=5), )
# Avoid needing display if plots aren't being shown import sys if "--noninteractive" in sys.argv: import matplotlib as mpl mpl.use("svg") import bookutil.latex as latex import control as ct import frccontrol as fct import matplotlib.pyplot as plt import numpy as np from numpy import concatenate plt.rc("text", usetex=True) def main(): J = 7.7500e-05 b = 8.9100e-05 Kt = 0.0184 Ke = 0.0211 R = 0.0916 L = 5.9000e-05 # fmt: off A = np.array([[-b / J, Kt / J], [-Ke / L, -R / L]]) B = np.array([[0], [1 / L]]) C = np.array([[1, 0]]) D = np.array([[0]])
error = np.nan_to_num(error) DX, BETA_INI = np.meshgrid(dx_grid, beta_ini_grid) plt.figure() plt.contourf( DX, BETA_INI, ) plt.show() plt.close() return error, dx_grid, beta_ini_grid, dx_grid_test # Usar latex en texto de figuras y agrandar tamaño de fuente plt.rc('text', usetex=True) plt.rcParams.update({'font.size': 15, 'text.latex.unicode': True}) # Obtenemos path para guardar archivos en el mismo directorio donde se ubica el script script_dir = os.path.dirname(os.path.abspath(__file__)) ################################################################################################# # Corre algoritmo matrix squaring # # # Decide si corre esta parte del algoritmo run_ms_algorithm = True # Parámetros físicos del algoritmo x_max = 5. nx = 201
_mpl = False try: import matplotlib import matplotlib.pyplot as plt from matplotlib.widgets import Slider matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 plt.style.use('ggplot') matplotlib.rcParams['font.size'] = 7 matplotlib.rcParams['lines.linewidth'] = 0.5 matplotlib.rcParams['xtick.major.size'] = 1.5 matplotlib.rcParams['ytick.major.size'] = 1.5 matplotlib.rcParams['axes.labelpad'] = 1 plt.rc('grid', linestyle="-", color='#dbdbdb') _mpl = True except ImportError: # pragma nocover pass class PyPlot2(Connector): def __init__(self): super(PyPlot2, self).__init__() self.robots = [] self.ellipses = [] if not _mpl: # pragma nocover raise ImportError(
m.plot(prediction) fig = fig = px.line(prediction.iloc[2912:], x='ds', y='yhat') fig.show() prediction.info() pred=prediction.iloc[3912:4248,[0,21]] pred['ds']=pd.to_datetime(pred.ds) pred.info() """#memvisualisasikan perbandingan data real dan hasil prediksi serta membuat rmse dan r2 dr model""" plt.figure(figsize=(16,8)) plt.rc('xtick', labelsize=16) plt.rc('ytick', labelsize=14) plt.plot(d_test['y'].values, label='Test') plt.plot(pred['yhat'].values, label='pred') plt.legend(loc='best') plt.show() from sklearn.metrics import r2_score r2=r2_score(d_test['y'], pred['yhat']) rms1 = np.sqrt(mean_squared_error(d_test['y'], pred['yhat'])) print(r2," , ",rms1) """**note:** selain mentune seasonality kita jg dapat mentune change_point perior scale dr model untuk menyesuaikan apakah hasil prediksi/ model akan mengikuti data set --- **note:** hati" saat melakukan tune agas model yang dibuat tidak overfit
def test_grid_regression(): # Regression test for a bug that meant that if the rc parameter # axes.grid was set to True, WCSAxes would crash upon initalization. plt.rc('axes', grid=True) fig = plt.figure(figsize=(3, 3)) WCSAxes(fig, [0.1, 0.1, 0.8, 0.8])
def parametric_omega(gamma, other_omega): if gamma == 0: return 0 if other_omega < gamma: return -gamma * lambertw( -other_omega * exp(-other_omega / gamma) / gamma, k=-1).real return -gamma * lambertw( -other_omega * exp(-other_omega / gamma) / gamma).real if __name__ == "__main__": xs = np.linspace(0, 3.0, 500) plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.plot(xs, [(2 - x) / (2 - 1) for x in xs], label=r"Possible $\Omega$ values for $K=2$") plt.plot(xs, [(3 - x) / (3 - 1) for x in xs], label=r"Possible $\Omega$ values for $K=3$") plt.plot(xs, [parametric_omega(1.0, x) for x in xs], label=r"$\gamma=1.0$", linestyle="dashed") plt.plot(xs, [parametric_omega(1.0926, x) for x in xs], label=r"$\gamma=1.0926$", linestyle="dashed") plt.xlim([0.0, 3.0]) plt.ylim([0.0, 2.0]) plt.xlabel(r"$\omega_{in}$", fontsize=14) plt.ylabel(r"$\omega_{out}$", fontsize=14)
def EventSubsetDisplay(tubes, quantities, PMTFlatMapPositive, tubes_to_plot, title="Charge", cutrange=[-1, -1], padding=10): """ tubes == np.array of PMTs that were hit quantities == np.array of PMT quantities (either charge or time) title == title to add to display cutrange == minimum and maximum values on plot (or set both -1 for default) """ PMTFlatMapPositive_values = [ PMTFlatMapPositive[tube] for tube in tubes_to_plot ] subset_x_values = np.array( [value[0] for value in PMTFlatMapPositive_values]) subset_y_values = np.array( [value[1] for value in PMTFlatMapPositive_values]) # set up dimensions for subset preimage with short tank data min_subplot_x_value = subset_x_values.min() - padding max_subplot_x_value = subset_x_values.max() + padding min_subplot_y_value = subset_y_values.min() - padding max_subplot_y_value = subset_y_values.max() + padding fig, ax = plt.subplots(figsize=[30, 30]) preimage = np.zeros(preimage_dimensions) subset_quantities = [] for idx, tube in enumerate(tubes): if cutrange[0] != cutrange[1]: if (cutrange[0] != -1 and quantities[idx] < cutrange[0]) or \ (cutrange[1] != -1 and quantities[idx] > cutrange[1]): continue for dx in range(-3, 4): for dy in range(-3, 4): if abs(dx) == 3 and abs(dy) == 3: continue if tube in tubes_to_plot: #print( "idx=", idx, " len(quantities)=",len(quantities), " tube=", tube, " len(PMTFlatMap)=", len(PMTFlatMapPositive)) preimage[PMTFlatMapPositive[tube][1] + dx, PMTFlatMapPositive[tube][0] + dy] = quantities[idx] subset_quantities.append(quantities[idx]) subset_quantities = np.array(subset_quantities) imgmin = subset_quantities.min() if cutrange[0] == -1 else cutrange[0] imgmax = subset_quantities.max() if cutrange[1] == -1 else cutrange[1] subset_image = preimage[min_subplot_y_value:max_subplot_y_value, min_subplot_x_value:max_subplot_x_value] im = ax.imshow(subset_image, extent=[ min_subplot_x_value, max_subplot_x_value, min_subplot_y_value, max_subplot_y_value ], vmin=imgmin, vmax=imgmax) fig.suptitle(title, fontsize=80) plt.rc('xtick', labelsize=24) plt.rc('ytick', labelsize=24) plt.xlabel('Distance CCW on perimeter from x-axis (cm)', fontsize=48) plt.ylabel('Y (cm)', fontsize=48) plt.set_cmap('gist_heat_r') # Create colourbar divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(im, cax=cax) cbar.ax.tick_params(labelsize=24) # Fix title height plt.tight_layout()
help='decides wether something gets printed to screen or not') # do the parsing: args = parser.parse_args() # process input arguments: files = args.files number_fish = len(files) if args.outroot is not None: outroot = args.outroot else: outroot = None # latex rendering of text if required: if args.latex is not None: if args.latex: plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) plt.rc('text', usetex=True) # start the plot: fig = plt.figure() # cycle over files: for file in files: # import the data: data = np.loadtxt(file) # get number of columns: n_col = data.shape[1] # get the x column: if args.x_column is not None: x_index = args.x_column else:
def plot_figA1(df, fcstnme, gis_path, hshallow_gp, hdeep_gp, hmuni_gp, zwells_gp): # Export parameters fontsze = 11 figsize = cm2inch(14, 18) plt.rcParams['font.size'] = fontsze plt.rc('font',**{'family':'sans-serif', 'sans-serif':['Arial']}) # # Set up labels if 'muni' in fcstnme: well_no = fcstnme.split('muni')[1] title = 'Forecast: Interface elevation ' + r'$\zeta_{\rm muni} $ ' + well_no elif fcstnme == 'fw_storage': df = df / (10**9) title = 'Forecast: Freshwater volume' # Load GIS data using gis_path wells_muni = gpd.GeoDataFrame.from_features(records(gis_path + 'wells_muni' + '.shp', ['name_model'])) coastline = gpd.read_file(gis_path + 'polyg_model' + '.shp') muni_coordinates = get_coordinates(muni_df) # Get coordinates of municipal wells xmuni = [coord[0] for name, coord in muni_coordinates.items()] ymuni = [coord[1] for name, coord in muni_coordinates.items()] # Merge dataframe info and geopandas geometry hshallow, hdeep, hmuni, zwells, ztdem, zert, hobs, zobs = merge_df_with_gpd(df, hshallow_gp, hdeep_gp, hmuni_gp, zwells_gp, gis_path) # Set up figure fig, axs = plt.subplots(2, 1, figsize=figsize, sharex=True, sharey=True, subplot_kw=dict(aspect='equal')) # fig.suptitle(title, fontsize = fontsze) axs = axs.ravel() cbar_label = '% decrease in ' + r'$\sigma_{\rm prior}$' + ' when obs. used' for i in range(2): coastline.plot(ax=axs[i], color='gray', alpha=0.4, edgecolor='k') # Plot coastline ax_divider = make_axes_locatable(axs[i]) cax = ax_divider.append_axes("right", size="5%", pad="1%") # If we're plotting data worth for municipal well forecasts if 'muni' in fcstnme: wells_muni[ wells_muni.name_model.str.endswith(fcstnme[1:]) ].plot(ax=axs[i], marker='o', markersize=40, facecolors='k', label=None) # Plot municipal wells at which forecast made idx = [idx for idx, well in enumerate(wells_muni.name_model) if fcstnme[1:] in well][0] axs[i].annotate(wells_muni.name_model[idx], (xmuni[idx], ymuni[idx]), xytext=(0, 5), textcoords='offset points', ha='center', va='bottom', fontsize = fontsze - 1) # First frame = head observations if i == 0: hobs.plot(ax=axs[i], column=fcstnme, marker='o', markersize=30, edgecolors='k', linewidths=0, cmap=plt.cm.viridis, legend=True, cax=cax, legend_kwds={'label': cbar_label}) # legend=True: tells Geopandas to add the colorbar # Label observation groups hshallow.plot(ax=axs[i], marker='p', markersize=50, facecolors='None', edgecolors='k', linewidths=0.5, label='Shallow wells') hdeep.plot(ax=axs[i], marker='o', markersize=35, facecolors='None', edgecolors='white', linewidths=1.2, label='Deep wells') hmuni.plot(ax=axs[i], marker='o', markersize=35, facecolors='None', edgecolors='k', linewidths=1.3, label='Municipal wells') axs[i].set_title('Worth of freshwater head observations (' + r'$\zeta_{\rm muni} $ ' + well_no + ' forecast)' , fontsize = fontsze) # Second frame = interface observations elif i == 1: zobs.plot(ax=axs[i], column=fcstnme, marker='o', markersize=30, cmap=plt.cm.viridis, legend=True, cax=cax, legend_kwds={'label': cbar_label}) # markersize=np.abs(zobs.residual)*2 # Label observation groups zwells.plot(ax=axs[i], marker='o', markersize=35, facecolors='None', edgecolors='white', linewidths=1.2, label='Deep wells') ztdem.plot(ax=axs[i], marker='p', markersize=50, facecolors='None', edgecolors='white', linewidths=0.5, label='TDEM') zert.plot(ax=axs[i], marker='o', markersize=60, facecolors='None', edgecolors='gray', linewidths=0.1, label='ERT') axs[i].set_title('Worth of interface observations (' + r'$\zeta_{\rm muni} $ ' + well_no + ' forecast)' , fontsize = fontsze) axs[i].legend(loc='upper left', facecolor='gray', framealpha=0.3, fontsize = fontsze) # Show x and y axis in km instead of m axs[i].xaxis.set_major_formatter(FuncFormatter(lambda x, pos: ('%.0f')%(x/1e3))) axs[i].yaxis.set_major_formatter(FuncFormatter(lambda x, pos: ('%.0f')%(x/1e3))) axs[i].set_ylabel('y (km)') axs[0].set_xlim(300000, 306000) axs[0].set_ylim(5267000, 5271000) axs[1].set_xlabel('x (km)') plt.tight_layout(rect=[0, 0, 1, 0.95]) plt.show() plt.savefig('FigA1_' + fcstnme + '.png', dpi = 600)
import time import re import datetime import pyActigraphy import sys sfp = '/home/ngrav/project' sys.path.append(sfp) from wearables.scripts import utils as wearutils import torch # plotting import matplotlib.pyplot as plt import seaborn as sns plt.rc('font', size=9) plt.rc('font', family='sans serif') plt.rcParams['pdf.fonttype'] = 42 plt.rcParams['ps.fonttype'] = 42 plt.rcParams['legend.frameon'] = False plt.rcParams['axes.grid'] = False plt.rcParams['legend.markerscale'] = 0.5 plt.rcParams['savefig.dpi'] = 600 sns.set_style("ticks") class raw2df(): ''' Description: The data was sent with {PID}_GA{y}.mtn names. We need to convert this raw data into numpy and pandas. First, we identify all valid files and
def plot_fig8(post_for, df_abs, fcstnme): # Export parameters fontsze = 11 figsize = cm2inch(9.5, 8) plt.rcParams['font.size'] = fontsze plt.rc('font',**{'family':'sans-serif', 'sans-serif':['Arial']}) # Prepare dataframe df_abs_subset = df_abs[df_abs.index.str.startswith(fcstnme)] # Replace column names with the following list (for the legend) cols = [r'$\sigma_{\rm\ post}$', # Posterior forecast stdev r'If $K$ field' + '\nknown', # hcond parameter group r'If $R$ known', # recharge parameter group r'If $\alpha_{\rm T}$ known'] # alpha parameter group df_abs_subset.columns = cols # Sort dataframe in descending order df_abs_subset = df_abs_subset.T df_abs_subset = df_abs_subset.sort_values(by=fcstnme, ascending=False) df_abs_subset = df_abs_subset.T # Set up a different color for each parameter group colors=[] for col in df_abs_subset.columns: if col == cols[0]: # posterior forecast stdev c = 'k' if col == cols[1]: # hcond parameter group c = 'tab:red' elif col == cols[2]: # recharge parameter group c = 'tab:blue' elif col == cols[3]: # alpha parameter group c = 'tab:green' colors.append(c) # Set up labels if 'muni' in fcstnme: well_no = fcstnme.split('muni')[1] # Get well number unit_stdev = 'm' unit_fcst = 'masl' Fmt = '%0.0f' fcst = post_for.loc[fcstnme, 'Mean'] title = 'Interface elevation ' + r'$\zeta_{\rm muni}$ ' + well_no + \ ' (%0.1f ' % (fcst) + unit_fcst + ')' elif fcstnme == 'fw_storage': df_abs_subset = df_abs_subset / (10**9) unit_stdev = 'km$^3$' unit_fcst = unit_stdev Fmt = '%0.1f' fcst = post_for.loc[fcstnme, 'Mean'] / (10**9) title = 'Freshwater volume ' + r'$V_{\rm f}$ (%0.1f ' % (fcst) + unit_fcst + ')' # Bar plot ax = df_abs_subset.plot(kind = 'bar', figsize = figsize, rot = 45, grid = True, color = colors, legend = None, width = 15, edgecolor = 'white', linewidth = 5) # Annotate the first bar differently (base posterior forecast uncertainty) for p in ax.patches[0:1]: sigma_base = p.get_height() ann = df_abs_subset.columns[0] ax.annotate(ann, (p.get_x() * 1.005, p.get_height() * 0.980), va='bottom', fontsize = fontsze - 1) # Annotate the other bars with 1) legend and 2) percent reduction in forecast uncertainty for i, p in enumerate(ax.patches[1:]): sigma = p.get_height() label = 100 * (sigma_base - sigma) / sigma_base # Compute percent reduction in forecast uncertainty ann = df_abs_subset.columns[i+1] + '\n' + '- ' + Fmt % (label) + ' %%' ax.annotate(ann, (p.get_x() * 1.005, p.get_height() * 0.980), va='bottom', fontsize = fontsze - 1) # Figure limits ax.set_ylim(0, sigma_base + sigma_base * 0.15) # Other figure parameters ax.set_axisbelow(True) x_axis = ax.axes.get_xaxis() x_axis.set_visible(False) ax.set_ylabel('Standard deviation ' + r'$\sigma$' + ' (' + unit_stdev + ')') plt.title(title, loc='left', fontsize = fontsze) plt.tight_layout() plt.show() plt.savefig('Fig8_' + fcstnme + '.png', dpi = 600)
def plot_fig5a(pst): # Export parameters fontsze = 11 figsze = cm2inch(9.5, 9.5) plt.rcParams['font.size'] = fontsze plt.rc('font',**{'family':'sans-serif', 'sans-serif':['Arial']}) # Load residuals & observations dataframes res = pst.res # Residuals obs = pst.observation_data # Observations # Group observations grouper = obs.groupby(obs.obgnme).groups # Drop the observation groups that are not to be plotted [grouper.pop(key, None) for key in ['fw_storage', 'hdomest']] [grouper.pop(key, None) for key in ['zwells', 'ztdem', 'zert']] # For each remaining observation group, define legend and marker type, size, color, edgecolor, linewidth grouper_lgd = {'hdeep': r'$h_{\rm f\ deep\ wells}$', 'hshallow': r'$h_{\rm f\ shallow\ wells}$','hmuni': r'$h_{\rm f\ pumping\ wells}$'} grouper_mkr = {'hdeep': '^', 'hshallow': 'o','hmuni': 's'} grouper_sz = {'hdeep': 120, 'hshallow': 70,'hmuni': 50} grouper_clr = {'hdeep': 'red', 'hshallow': 'lime', 'hmuni': 'black'} grouper_edgeclr = {'hdeep': 'black', 'hshallow': 'black','hmuni': None} grouper_linewdth = {'hdeep': 0.5, 'hshallow': 0.5, 'hmuni': None} # Start plotting fig, ax = plt.subplots(figsize=figsze) # For each observation group for groupname, obsnames in grouper.items(): obs_g = obs.loc[obsnames, :] obs_g.loc[:, 'sim'] = res.loc[obsnames, 'modelled'] obs_g.loc[:,'res'] = obs_g.sim - obs_g.obsval # Define residual = sim - obs obs_g = obs_g.loc[obs_g.weight > 0, :] # Exclude observations with weight = 0 ax.scatter([obs_g.obsval], [obs_g.sim], label=grouper_lgd[groupname], marker=grouper_mkr[groupname], s=grouper_sz[groupname], color=grouper_clr[groupname], edgecolors=grouper_edgeclr[groupname], linewidths=grouper_linewdth[groupname]) # Modify limits of the scatter plot Max = 3 Min = 0 ax.plot([Min,Max], [Min,Max], 'k--', lw=1.0) # Plot the 1:1 diagonal line ax.set_xlim(Min,Max) ax.set_ylim(Min,Max) # Other figure parameters ax.axis('square') ax.grid() ax.set_axisbelow(True) # Order the legend handles, labels = plt.gca().get_legend_handles_labels() order = [2,1,0] ax.legend([handles[idx] for idx in order], [labels[idx] for idx in order], loc='upper left') ax.set_xlabel('Observed (m)', labelpad=0.1) ax.set_ylabel('Simulated (m)', labelpad=0.1) ax.set_title('Freshwater heads ' + r'$h_{\rm f}$', loc='left', fontsize=fontsze) plt.tight_layout() plt.show() plt.savefig('Fig5A.png', dpi = 600)
# first_date = Date_total.iloc[0] # last_date = Date_total.iloc[-1] # first_date = first_date[6:]+'-'+first_date[0:2]+'-'+first_date[3:5] # last_date = last_date[6:]+'-'+last_date[0:2]+'-'+str(int(last_date[3:5])+1) # date_total = np.arange(first_date, last_date, dtype='datetime64[D]')[:,None] first_date = '2020-03-06' #first_date[6:]+'-'+first_date[0:2]+'-'+first_date[3:5] last_date = '2021-03-11' #last_date[6:]+'-'+last_date[0:2]+'-'+str(int(last_date[3:5])+1) date_total = np.arange(first_date, last_date, dtype='datetime64[D]') # date_total = Date_total sf = 1e-4 plt.rc('font', size=30) #%% #Current Suspectious fig, ax = plt.subplots() ax.plot(date_total, S_pred_mean / sf, 'k-', lw=5) plt.fill_between(date_total, \ (S_pred_mean+S_pred_std)/sf, \ (S_pred_mean-S_pred_std)/sf, \ facecolor=(0.1,0.2,0.5,0.3), interpolate=True) # ax.set_xlim(0-0.5,180) # ax.set_ylim(0-0.5,6000+0.5) ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%y')) ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7))
def plot_fig9(post_for, df_stdev, fcstnme): # Export parameters fontsze = 11 plt.rcParams['font.size'] = fontsze plt.rc('font',**{'family':'sans-serif', 'sans-serif':['Arial']}) figsze = cm2inch(19, 6) # Prepare dataframe df_stdev_subset = df_stdev[df_stdev.index.str.startswith(fcstnme)] # Replace column names with the following list (for the legend) cols = ['No data ' + r'($\sigma_{\rm prior}$)', # Prior forecast stdev (no observations) r'+ $h_{\rm shallow}$', # h shallow observation group r'+ $h_{\rm deep}$', # h deep observation group r'+ $h_{\rm muni}$', # h muni observation group r'+ $\zeta_{\rm deep}$', # zeta deep well observation group r'+ $\zeta_{\rm TDEM}$', # zeta TDEM observation group r'+ $\zeta_{\rm ERT}$', # zeta ERT observation group 'All data\n' + r'($\sigma_{\rm post}$)', # Posterior forecast stdev (all observations) '+ All ' + r'$h$', # All h observations '+ All\n' + r'$\zeta_{\rm geophy}$', # All geophysical zeta observations '+ All ' + r'$\zeta$'] # All zeta observations df_stdev_subset.columns = cols # Sort dataframe in descending order df_stdev_subset = df_stdev_subset.T df_stdev_subset = df_stdev_subset.sort_values(by=fcstnme, ascending=False) df_stdev_subset = df_stdev_subset.T # Set up a different color for each observation group colors=[] for col in df_stdev_subset.columns: if col == cols[0]: # prior forecast stdev c = 'tab:orange' if col == cols[1]: # hshallow c = 'chartreuse' elif col == cols[2]: # hdeep c = 'red' elif col == cols[3]: # hmuni c = 'grey' elif col == cols[4]: # zdeep c = 'aquamarine' elif col == cols[5]: # ztdem c = 'cornflowerblue' elif col == cols[6]: # zert c = 'tab:blue' elif col == cols[7]: # posterior forecast stdev c = 'k' elif col == cols[8]: # hobs c = 'tab:green' elif col == cols[9]: # zgeo c = 'tab:purple' elif col == cols[10]: # zobs c = 'navy' colors.append(c) # Set up labels if 'muni' in fcstnme: well_no = fcstnme.split('muni')[1] unit_stdev = 'm' unit_fcst = 'm/sea level' fcst = post_for.loc[fcstnme, 'Mean'] title = 'Interface elevation ' + r'$\zeta_{\rm muni} $ ' + well_no + \ ' (%0.1f ' % (fcst) + unit_fcst + ')' elif fcstnme == 'fw_storage': df_stdev_subset = df_stdev_subset / (10**9) unit_stdev = 'km$^3$' unit_fcst = unit_stdev fcst = post_for.loc[fcstnme, 'Mean'] / (10**9) title = 'Freshwater volume ' + r'$V_{\rm f}$ (%0.1f ' % (fcst) + unit_fcst + ')' # Bar plot ax = df_stdev_subset.plot(kind = 'bar', figsize = figsze, rot = 45, grid = True, color = colors, legend = None, width = 15, edgecolor = 'white', linewidth = 5) # Cycle through default colors # Annotate the first bar differently (base prior forecast uncertainty) for p in ax.patches[0:1]: sigma_base = p.get_height() ann = df_stdev_subset.columns[0] #stdev_symbol ax.annotate(ann, (p.get_x() * 1.005, p.get_height() * 0.960), va='bottom', fontsize = fontsze - 1) # Annotate the other bars with 1) legend and 2) percent reduction in prior forecast uncertainty for i, p in enumerate(ax.patches[1:]): sigma = p.get_height() label = 100 * (sigma_base - sigma) / sigma_base ann = df_stdev_subset.columns[i+1] + '\n' + '-%0.1f %%' % (label) ax.annotate(ann, (p.get_x() * 1.005, p.get_height() * 0.900), va='bottom', fontsize = fontsze - 1) # Figure limits ax.set_ylim(0, sigma_base + sigma_base * 0.1) ax.set_axisbelow(True) # Other figure parameters x_axis = ax.axes.get_xaxis() x_axis.set_visible(False) ax.set_ylabel('Standard deviation ' + r'$\sigma$' + ' (' + unit_stdev + ')') plt.title(title, loc='left', fontsize = fontsze) plt.tight_layout() plt.show() plt.savefig('Fig9_' + fcstnme + '.png', dpi = 600)
from sklearn.cross_validation import StratifiedKFold from sklearn.metrics import roc_curve, auc, roc_auc_score from sklearn.feature_selection import SelectFwe from scipy import signal from scipy.fftpack import fft, fftshift from scipy import interp params = {'legend.fontsize': 'large', 'figure.figsize': (5, 3), 'axes.labelsize': 'x-large', 'axes.titlesize': 'x-large', 'xtick.labelsize': 'x-large', 'ytick.labelsize': 'x-large'} font = {'weight': 'bold', 'size': 22} plt.rc('font', **font) from sklearn.feature_selection import VarianceThreshold from sklearn.feature_selection import SelectPercentile, f_classif, GenericUnivariateSelect, SelectKBest, chi2 from sklearn.feature_selection import RFE import os import seaborn as sns import pandas as pd import csv from scipy import stats import brainiak import brainiak.funcalign.srm import sys projectDir='/jukebox/norman/amennen/prettymouth/' DMNmask='/jukebox/norman/amennen/MNI_things/Yeo_JNeurophysiol11_MNI152/Yeo_Network7mask_reoriented_resampledBOLD.nii.gz' fmriprep_dir=projectDir + '/derivatives/fmriprep'
def plot_fig7(df_prior, df_post, fcstnme): # Export parameters fontsze = 11 figsze = cm2inch(9.5,9.5) plt.rcParams['font.size'] = fontsze plt.rc('font',**{'family':'sans-serif', 'sans-serif':['Arial']}) # Prepare dataframes df_prior_subset = df_prior[df_prior.index.str.startswith(fcstnme)] df_post_subset = df_post[df_post.index.str.startswith(fcstnme)] # Set up labels if 'zmuni' in fcstnme: well_no = fcstnme.split('muni')[1] # Get well number clean_nme = r'$\zeta$' unit = 'masl' Fmt = '%0.0f' xlabel = 'Interface elevation ' + r'$\zeta_{\rm muni} $' + well_no + ' (' + unit + ')' elif fcstnme == 'fw_storage': df_prior_subset = df_prior_subset / (10**9) # From m3 to km3 df_post_subset = df_post_subset / (10**9) # From m3 to km3 clean_nme = r'$V_{\rm f}$' unit = 'km$^3$' Fmt = '%0.1f' xlabel = 'Freshwater volume ' + r'$V_{\rm f}$' + ' (' + unit + ')' # Start plot plt.figure(figsize=figsze) ax = plt.subplot(1,1,1) # Plot prior distribution (Gaussian) mean = df_prior_subset.Mean[0] stdev = df_prior_subset.Stdev[0] x1, y1 = pyemu.plot_utils.gaussian_distribution(mean, stdev) label = 'Prior ' + clean_nme + ': ' + Fmt % (mean) + ' \u00B1 ' + Fmt % (2 * stdev) + ' ' + unit ax.plot(x1, y1, linestyle='dashed', color = 'grey', label = label) # Plot posterior distribution (Gaussian) mean = df_post_subset.Mean[0] stdev = df_post_subset.Stdev[0] x2, y2 = pyemu.plot_utils.gaussian_distribution(mean, stdev) label = 'Posterior ' + clean_nme + ': ' + Fmt % (mean) + ' \u00B1 ' + Fmt % (2 * stdev) + ' ' + unit ax.fill_between(x2, 0, y2, alpha=0.5, color = 'grey', label = label) # Figure limits Max = max(y1.max(), y2.max()) ax.set_ylim(0, Max + Max * 0.3) # Other figure parameters ax.legend(loc = 'upper left') ax.set_xlabel(xlabel) ax.set_ylabel('Probability density') plt.tight_layout() plt.show() plt.savefig('Fig7_' + fcstnme + '.png', dpi = 600)
def prepare_data(data,bin_tails=False): x,y = data # Eliminate y offset y -= np.mean(y) return x,y T = [0,10,20,30,40,50,60,70,72,75,80] T_display = [30,60,72,80] display_count = 0 H_c = np.zeros_like(T) H_c_err = np.zeros_like(T) plt.rcParams.update({'font.size': 20}) plt.rc('axes', labelsize=26) fig, axes = plt.subplots(2,2,sharey="row",sharex="row") fig.subplots_adjust(hspace=0.35,wspace=0.05) axes = axes.ravel() for i,temperature in enumerate(["00","10","20","30","40","50","60","70","72","75","80"]): data_x,data_y = prepare_data(np.loadtxt(f"../data/sample_C6_{temperature}.DAT",unpack=True)) X = np.linspace(0.95*min(data_x),1.05*max(data_x),1000) # Split in ascending / descending branch xmin, xmax = np.argmin(data_x), np.argmax(data_x) complement_mask = np.ones(len(data_x),dtype=bool) complement_mask[xmax:xmin] = False x_split = [data_x[complement_mask], data_x[xmax:xmin]]
def draw_environment(self, sim, interacts, image_file=None, tick=None): # --- Plot parameters --- plt.clf() plt.figure(figsize=(fig_size, fig_size), dpi=25) plt.axis('off') plt.title('Environment', fontsize=font_size) plt.rc('xtick', labelsize=font_size) plt.rc('ytick', labelsize=font_size) # --- Show resource and danger --- res = plt.imshow(self.resource.T, cmap='Greens', alpha=1) dng = plt.imshow(self.danger.T, cmap='Reds', alpha=0.4) if tick is not None: plt.text(3, -5, 'Tick: {}'.format(tick), fontsize=font_size) ''' plt.colorbar(res).set_label('Resource') plt.colorbar(dng).set_label('Danger') ''' # --- Show agents --- for agent_id, agent in sim.all_agents.items(): self.draw_agent(agent) for other_agent_id, score in agent.acquaint.items(): try: other_agent = sim.all_agents[other_agent_id] self.draw_relationship(agent, other_agent, score) except: pass # --- Show current interactions --- if len(interacts) > 1: for agent_id, oth_agent_id in interacts: x1, y1 = sim.all_agents[agent_id].position x2, y2 = sim.all_agents[oth_agent_id].position plt.plot([x1, x2], [y1, y2], color='cyan', linestyle=':', linewidth=7) # --- Show Monolith if self.monolith.seen == True: pos_x, pos_y = self.monolith.position plt.plot(pos_x, pos_y, marker="*", markersize=2 * font_size, color='gold') if image_file: plt.savefig(image_file) plt.close()
# imports import gemini3d.read import os import numpy as np import matplotlib.pyplot as plt from plotGDI_tools import padstr # set some font sizes SMALL_SIZE = 14 MEDIUM_SIZE = 16 BIGGER_SIZE = 20 plt.rc('font', size=SMALL_SIZE) # controls default text sizes plt.rc('axes', titlesize=BIGGER_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title # location of simulation output home = os.path.expanduser("~") direc = home + "/simulations/raid/TGI_MR/" plotdir = direc + "/customplots2/" if not os.path.isdir(plotdir): os.mkdir(plotdir) parmlbl = "ne" # config and grid data print("...Loading config and grid...") cfg = gemini3d.read.config(direc)
#程序文件Pex2_47.py import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm mu0 = [-1, 0] s0 = [0.5, 1] x = np.linspace(-7, 7, 100) plt.rc('font', size=15) plt.rc('text', usetex=True) plt.rc('axes', unicode_minus=False) f, ax = plt.subplots(len(mu0), len(s0), sharex=True, sharey=True) for i in range(2): for j in range(2): mu = mu0[i] s = s0[j] y = norm(mu, s).pdf(x) ax[i, j].plot(x, y) ax[i, j].plot(1, 0, label="$\\mu$ = {:3.2f}\n$\\sigma$ = {:3.2f}".format(mu, s)) ax[i, j].legend(fontsize=12) ax[1, 1].set_xlabel('$x$') ax[0, 0].set_ylabel('pdf($x$)') plt.savefig('figure2_47.png') plt.show()
t_c=0.12, St=0.28, weighting="A") configs[config]["f_{peak}"][j] = f_peak.to(ureg.turn / ureg.s).magnitude configs[config]["SPL_A"][j] = SPL configs[config][ "f_{peak}"] = configs[config]["f_{peak}"] * ureg.turn / ureg.s solidity = solidity[1] #convert back to array from tuple # Plotting commands plt.ion() fig1 = plt.figure(figsize=(12, 12), dpi=80) plt.rc('axes', axisbelow=True) plt.show() style = {} style["linestyle"] = ["-", "-", "-", "-", "--", "--", "--", "--"] style["marker"] = ["s", "o", "^", "v", "s", "o", "^", "v"] style["fillstyle"] = [ "full", "full", "full", "full", "none", "none", "none", "none" ] style["markersize"] = 10 #Maximum takeoff weight plt.subplot(2, 2, 1) for i, config in enumerate(configs): c = configs[config] plt.plot(solidity,
print 'NO ' + data_path missing_file = True else: ws = np.load(data_path) acc_tmp.append(ws['accu']) ws.close() all_mean[i] = np.mean(acc_tmp) all_se[i] = np.std(acc_tmp) / math.sqrt(args.nsubjs) #if missing_file: # sys.exit('missing file') # set font size font = {'family': 'serif', 'size': 10} plt.rc('text', usetex=True) plt.rc('font', **font) aspectratio = 5 idx = range(len(algo_list)) plt.figure() error_config = {'ecolor': '0'} rects = plt.bar(idx, all_mean, yerr=all_se, align='center', error_kw=error_config) plt.xticks(idx, name, rotation='vertical') plt.ylabel('Accuracy')
from matplotlib import pyplot as plt font = {'family': 'LiSu', 'weight': 'bold', 'size': '16'} plt.rc('font', **font) # 步骤一(设置字体的更多属性) plt.rc('axes', unicode_minus=False) # 步骤二(解决坐标轴负数的负号显示问题) a = [ "战狼2", "速度与激情8", "功夫瑜伽", "西游伏妖篇", "变形金刚5:最后的骑士", "摔跤吧!爸爸", "加勒比海盗5:死无对证", "金刚:骷髅岛", "极限特工:终极回归", "生化危机6:终章", "乘风破浪", "神偷奶爸3", "智取威虎山", "大闹天竺", "金刚狼3:殊死一战", "蜘蛛侠:英雄归来", "悟空传", "银河护卫队2", "情圣", "新木乃伊" ] b = [ 56.01, 26.94, 17.53, 16.49, 15.45, 12.96, 11.8, 11.61, 11.28, 11.12, 10.49, 10.3, 8.75, 7.55, 7.32, 6.99, 6.88, 6.86, 6.58, 6.23 ] plt.bar(range(len(a)), b, 0.4) plt.xticks(range(len(a)), a, rotation=90) plt.show()
con_mat = pd.crosstab(y_test, y_pred, rownames=['예측값'], colnames=['관측값']) print(con_mat) print((con_mat[0][0] + con_mat[1][1] + con_mat[2][2]) / len(y_test)) # 0.9777777777 print(ml.score(x_test, y_test)) # 0.977777777 # 시각화 import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from matplotlib import font_manager, rc font_name = font_manager.FontProperties( fname="c:/Windows/Fonts/malgun.ttf").get_name() plt.rc('font', family=font_name) #그래프에서 한글깨짐 방지용 def plot_decision_region(X, y, classifier, test_idx=None, resolution=0.02, title=''): markers = ('s', 'x', 'o', '^', 'v') # 점표시 모양 5개 정의 colors = ('r', 'b', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) #print('cmap : ', cmap.colors[0], cmap.colors[1], cmap.colors[2]) # decision surface 그리기
# #%% e = np.random.standard_normal(100) y = np.zeros(100) y[0] = e[0] for i in range(1, 100): y[i] = y[i-1] + e[i] #%% %matplotlib inline import matplotlib.pyplot as plt plt.rc('figure', figsize=(16,6)) plt.plot(y) #%% # ## Problem: Nested Loops # # Begin by loading momentum data used in an earlier lesson. Compute a # 22-day moving-window standard deviation for each of the columns. Store # the value at the end of the window. # # When finished, make sure that `std_dev` is a `DataFrame` and # plot the annualized percentage standard deviations using: # # ```python # ann_std_dev = 100 * np.sqrt(252) * std_dev
count = 0 for each_product_record in product_records_list: cpc_axis.append(float(each_product_record['calc_cpc'])) stop_date.append(each_product_record['date_stop']) ctr_axis.append(float(each_product_record['calc_ctr'])) print(each_product_record['campaign_name']) if each_product_record['purchase_rate'] == '': purchase_rate_axis.append(0) else: purchase_rate_axis.append(float(each_product_record['purchase_rate'])) if each_product_record['capital_roi'] == '': capital_roi.append(0) else: capital_roi.append(float(each_product_record['capital_roi'])) # print(item) plt.rc('xtick', labelsize=6) plt.rc('ytick', labelsize=6) plt.figure() plt.subplot(221) plt.xticks(rotation=45, ha="right") plt.plot(stop_date,cpc_axis,'-o') plt.title('Cpc') plt.grid(True) plt.subplot(222) plt.xticks(rotation=45, ha="right") plt.plot(stop_date,ctr_axis,'-o') plt.title('Ctr') plt.grid(True) plt.subplot(223) plt.xticks(rotation=45, ha="right") plt.plot(stop_date,purchase_rate_axis,'-o')
#! /usr/bin/python import pandas as pd import matplotlib.pyplot as plt import numpy as np plt.rc('axes', titlesize=16) # fontsize of the axes title plt.rc('axes', labelsize=16) # fontsize of the x and y labels plt.rc('xtick', labelsize=12) # fontsize of the tick labels plt.rc('ytick', labelsize=12) # fontsize of the tick labels plt.rc('legend', fontsize=12) # legend fontsize #plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title raw_data = {'graph': ['Youtube', 'LJ', 'Pokec', 'R-MATI', 'R-MATII'], 'c1': [16.1344/16.1344, 90.5813/90.5813, 32.1934/32.1934, 12.6965/12.6965, 50.7354/50.7354], 'c2': [16.1344/5.5074, 90.5813/48.601, 32.1934/20.7189, 12.6965/10.7273, 50.7354/42.7774], 'c3': [16.1344/5.2948, 90.5813/47.7471, 32.1934/20.4841, 12.6965/10.6896, 50.7354/42.607], 'c4': [16.1344/4.7289, 90.5813/45.5692, 32.1934/19.747, 12.6965/10.519, 50.7354/41.9917], 'c5': [16.1344/3.888, 90.5813/40.9439, 32.1934/17.9292, 12.6965/9.7478, 50.7354/38.9701], 'c6': [16.1344/1.4022, 90.5813/9.7264, 32.1934/3.8728, 12.6965/2.1245, 50.7354/8.6928], 'c7': [16.1344/1.4053, 90.5813/9.7447, 32.1934/3.9781, 12.6965/2.1248, 50.7354/8.7066], 'c8': [16.1344/11.203, 90.5813/116.173, 32.1934/50.658, 12.6965/27.400, 50.7354/109.523], 'c9': [16.1344/5.4649, 90.5813/51.455, 32.1934/22.1605, 12.6965/11.5924, 50.7354/46.5335] } df = pd.DataFrame(raw_data, columns = ['graph', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9']) fuck_label=('c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9') # Setting the positions and width for the bars pos = list(range(len(df['c1']))) width = 0.1 ecolor='k'
#!/usr/bin/env python # coding: utf-8 # In[9]: import time import numpy as np import matplotlib.pyplot as plt plt.rc('font', family='Malgun Gothic') class Matmul: def __init__(self, W): self.params = [W] self.grads = [np.zeros_like(W)] self.x = None # 순전파 def forward(self, x): W, = self.params out = np.dot(x, W) self.x = x return out # 역전파 def backward(self, dout): W, = self.params x = self.x dx = np.dot(dout, W.T) dW = np.dot(x.T, dout) self.grads[0][...] = dW # 깊은 복사
def latent_viz_pure(args, net, e, sess, data_loader): # Create dict of functions to choose next batch next_batch_dict = { 'passive': data_loader.next_batch_pass, 'medium1': data_loader.next_batch_med1, 'medium2': data_loader.next_batch_med2, 'aggressive': data_loader.next_batch_agg } # Generate samples data_loader.batchptr_pass = 0 data_loader.batchptr_med1 = 0 data_loader.batchptr_med2 = 0 data_loader.batchptr_agg = 0 full_sample_pass = gen_samples(args, net, sess, data_loader.batchptr_pass, data_loader.n_batches_pass, next_batch_dict, 'passive') full_sample_med1 = gen_samples(args, net, sess, data_loader.batchptr_med1, data_loader.n_batches_med1, next_batch_dict, 'medium1') full_sample_med2 = gen_samples(args, net, sess, data_loader.batchptr_med2, data_loader.n_batches_med2, next_batch_dict, 'medium2') full_sample_agg = gen_samples(args, net, sess, data_loader.batchptr_agg, data_loader.n_batches_agg, next_batch_dict, 'aggressive') # Select random subset of values in full set of samples ind_pass = random.sample(xrange(len(full_sample_pass)), 2000) ind_agg = random.sample(xrange(len(full_sample_agg)), 2000) ind_med1 = random.sample(xrange(len(full_sample_med1)), 2000) ind_med2 = random.sample(xrange(len(full_sample_med2)), 2000) # # Save samples to csv # print 'Saving to csv...' # np.savetxt('samples_passive.csv', full_sample_pass[ind_pass], delimiter=',') # np.savetxt('samples_aggressive.csv', full_sample_agg[ind_agg], delimiter=',') # np.savetxt('samples_medium1.csv', full_sample_med1[ind_med1], delimiter=',') # np.savetxt('samples_medium2.csv', full_sample_med2[ind_med2], delimiter=',') # print 'done' # Plot and save results print 'saving and exiting.' plt.cla() plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.plot(full_sample_pass[ind_pass, 0], full_sample_pass[ind_pass, 1], 'bx', label='Passive') plt.plot(full_sample_agg[ind_agg, 0], full_sample_agg[ind_agg, 1], 'ro', label='Aggressive') plt.plot(full_sample_med1[ind_med1, 0], full_sample_med1[ind_med1, 1], 'gp', label='Medium 1') plt.plot(full_sample_med2[ind_med2, 0], full_sample_med2[ind_med2, 1], 'cd', label='Medium 2') plt.ylim(-5, 5) plt.xlim(-5, 5) plt.xlabel(r'$z_1$', fontsize=16) plt.ylabel(r'$z_2$', fontsize=16) plt.title('Epoch ' + str(e)) plt.legend(loc='upper right', numpoints=1) plt.grid() plt.savefig('./images_recurrent/latent_viz_' + str(e) + '.png')
import matplotlib.pyplot as plt import numpy as np import os # ------------------------------------------------------------------------------# plt.rc("text", usetex=True) plt.rc("font", family="serif") plt.rc("font", size=12) def plot_single(data, legend, title, col=(0, 1)): plt.figure(0) plt.plot(data[:, col[0]], data[:, col[1]], label=legend) plt.title(title) plt.xlabel("arc length") plt.ylabel("$p$ difference") plt.grid(True) plt.legend() # ------------------------------------------------------------------------------# def save_single(filename, folder, figure_id=0, extension=".pdf"): if not os.path.exists(folder): os.makedirs(folder) plt.figure(figure_id)