def update(self, params, pdata, ptype = 'temp'): cfg = params['cfg'] cur_t = params['cur'] gxsec = params['gxsec'] self.ax.cla() # this is a brute-force way to update. I don't know how to update errorbar correctly. if ptype == 'temp': self.ax.axis([cur_t-gxsec, cur_t, cfg['tempmin'], cfg['tempmax']]) # [xmin,xmax,ymin,ymax] elif ptype == 'freq': self.ax.axis([cur_t-gxsec, cur_t, cfg['freqmin'], cfg['freqmax']]) # [xmin,xmax,ymin,ymax] plt.axhspan(cfg["freqnorm"], cfg["freqmax"], facecolor='#eeeeee', alpha=0.5) else: self.ax.axis([cur_t-gxsec, cur_t, 0, 100]) # [xmin,xmax,ymin,ymax] pkgid = 0 for t in pdata: x = t.getlistx() y = t.getlisty() e = t.getlisto() self.ax.plot(x,y,scaley=False,color=params['pkgcolors'][pkgid], label='PKG%d'%pkgid) self.ax.errorbar(x,y,yerr=e, lw=.2, color=params['pkgcolors'][pkgid], label = '') pkgid += 1 # we need to update labels everytime because of cla() self.ax.set_xlabel('Time [S]') if ptype == 'temp': self.ax.set_ylabel('Core temperature [C]') elif ptype == 'freq': self.ax.set_ylabel('Frequency [GHz]') else: self.ax.set_ylabel('Unknown') self.ax.legend(loc='lower left', prop={'size':9})
def runsimplot(self): """ Viz of the MC results """ tdmin = self.iniest.td - 3.0*self.iniest.tderr tdmax = self.iniest.td + 3.0*self.iniest.tderr fig = plt.figure(figsize=(6, 3)) fig.subplots_adjust(top=0.95, bottom=0.2) plt.scatter(self.simtruedelays, self.simmesdelays - self.simtruedelays) plt.xlim(tdmin, tdmax) plt.xlabel("True delay [day]") plt.ylabel("Measurement error [day]") plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhline(0, color="black", linestyle="-", zorder=20) plt.axhline(- self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhline(+ self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhspan(-self.outest.tderr, self.outest.tderr, xmin=0, xmax=1, lw=0, color="red", alpha=0.2) #plt.ylim(- 2.0*self.iniest.tderr, + 2.0*self.iniest.tderr) plt.figtext(0.15, 0.8, "Total/initial error ratio: %.2f" % self.totalratio) #ax = plt.gca() #plt.figtext(0.15, 0.8, "Intrinsic/initial error ratio: %.2f" % self.intrinsicratio) #plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) #plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) #plt.axvline(self.outest.td, color="red", linestyle="-", zorder=20) plt.savefig(os.path.join(self.plotdir, "measvstrue.png")) plt.close()
def ScatterPlot(TransitionForces,ListOfSepAndFits,ExpectedContourLength, OutDir): """ Makes a scatter plot of the contour length and transition forces Args: TransitionForces: array, each element the transition region for curve i ListOfSepAndFits: array, each element the output of GetWLCFits ExpectedContourLength: how long we expect the construct to be OutDir: base directory, for saving stuff """ L0Arr = [] TxArr = [] for (SepNear,FitObj),TransitionFoces in zip(ListOfSepAndFits, TransitionForces): MedianTx = np.median(TransitionFoces) L0,Lp,_,_ = FitObj.Params() L0Arr.append(L0) TxArr.append(MedianTx) # go ahead an throw out ridiculous data from the WLC, where transition # normalize the contour length to L0 L0Arr = np.array(L0Arr)/ExpectedContourLength # convert to useful units L0Plot = np.array(L0Arr) TxPlot = np.array(TxArr) * 1e12 fig = pPlotUtil.figure(figsize=(12,12)) plt.subplot(2,2,1) plt.plot(L0Plot,TxPlot,'go',label="Data") alpha = 0.3 ColorForce = 'r' ColorLength = 'b' plt.axhspan(62,68,color=ColorForce,label=r"$F_{\rm tx}$ $\pm$ 5%", alpha=alpha) L0BoxMin = 0.9 L0BoxMax = 1.1 plt.axvspan(L0BoxMin,L0BoxMax,color=ColorLength, label=r"L$_{\rm 0}$ $\pm$ 10%",alpha=alpha) fudge = 1.05 # make the plot boundaries OK MaxX = max(L0BoxMax,max(L0Plot))*fudge MaxY = 90 plt.xlim([0,MaxX]) plt.ylim([0,MaxY]) pPlotUtil.lazyLabel("",r"F$_{\rm overstretch}$ (pN)", "DNA Characterization Histograms ",frameon=True) ## now make 1-D histograms of everything # subplot of histogram of transition force HistOpts = dict(alpha=alpha,linewidth=0) plt.subplot(2,2,2) TransitionForceBins = np.linspace(0,MaxY) plt.hist(TxPlot,bins=TransitionForceBins,orientation="horizontal", color=ColorForce,**HistOpts) pPlotUtil.lazyLabel("Count","","") plt.ylim([0,MaxY]) plt.subplot(2,2,3) ContourBins = np.linspace(0,MaxX) plt.hist(L0Plot,bins=ContourBins,color=ColorLength,**HistOpts) pPlotUtil.lazyLabel(r"$\frac{L_{\rm WLC}}{L_0}$","Count","") plt.xlim([0,MaxX]) pPlotUtil.savefig(fig,"{:s}Out/ScatterL0vsFTx.png".format(OutDir))
def plot_daily_schedule(df, se, label): n = se.values() fig, ax = plt.subplots() av_start = [] av_end = [] for i in range(len(se)): dates = n[i][0] t_start = n[i][1] t_end = n[i][2] # plot date vs. start time plt.plot(dates, t_start , 'o', color='#2396D4', alpha=0.5) # plot date vs. end time plt.plot(dates, t_end, 'o', color='#FF7878', alpha=0.5) avg_start, std_start = avg_time(t_start) avg_end, std_end = avg_time(t_end) av_start.append(avg_start) av_end.append(avg_end) total_avg_start, total_std_start = avg_time(av_start) total_avg_end, total_std_end = avg_time(av_end) tmin_start = (total_avg_start - total_std_start).time() tmax_start = (total_avg_start + total_std_start).time() tmin_end = (total_avg_end - total_std_end).time() tmax_end = (total_avg_end + total_std_end).time() p = plt.axhspan(tmin_start, tmax_start, fc='#2396D4', ec='#2396D4' , alpha=0.3) p = plt.axhspan(tmin_end, tmax_end, fc= '#FF7878', ec='#FF7878', alpha=0.3) a0 = dt.datetime(1900,1,1,1,0,0) dr = [a0 + dt.timedelta(hours=a) for a in range(24) if a%3==0] dr2 = [t.time() for t in dr] plt.ylim(dt.datetime(1900,1,1,0,0,0).time(),dt.datetime(1900,1,1,23,59,59).time()) plt.xticks(rotation=20) ax.set_yticks(dr2) hfmt = md.DateFormatter('%m.%d') ax.xaxis.set_major_formatter(hfmt) plt.ylabel('Time of day [hr]') plt.title('Daily Work Schedule') ax.text(0.02, 0.9, label, transform=ax.transAxes, fontsize=24, va='top', ha='left', color='gray') plt.xlim(min(df.date)- dt.timedelta(days=4), max(df.date) + dt.timedelta(days=1)) plt.xlabel('Date') plt.text(0.03,0.365, "start work", ha='left', transform=ax.transAxes, color='#1F1AB2', fontsize=12) plt.text(0.03,0.675, "leave work", ha='left', transform=ax.transAxes, color='#AB2B52', fontsize=12) ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5) ax.xaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5) ax.set_axisbelow(True) fig.tight_layout() plt.savefig(img_dir+'schedule_'+label.replace(" ",'')+'.png', format="png", dpi=500)
def plot_cs(cp, filename=None): "cp is a CsParser Object" bar_len=10 bar_gap=5 if not len(cp.cpus): return plt.xlabel("time(ns)") plt.ylabel("cpu") plt.title("context switch chart") axd=cp.get_axis() plt.axis(axd) for cpu in cp.cpus: xy=cp.get_cpu_xy(cpu) lx, ly = 0, 0 for x, y in xy: if lx != 0: plt.axhspan(cpu*3+0.1, (cpu+1)*3-0.1, xmin=float(lx)/float(axd[1]), xmax=float(x)/float(axd[1]), facecolor=cmap[ly], alpha=0.5) lx, ly = x, y plt_show(filename)
def save(x, K1, K2, R, var1, var2, l, n, normalize, output_dir, save_dat, save_plot): out_fname = '%s-%s_l=%d_n=%d'%(var1,var2,l,n) if save_dat: np.savetxt(os.path.join(output_dir, out_fname+'.dat'), np.vstack((x, K1, K2)).T) if save_plot: varnames = {'c': r'c', 'c2': r'c^2', 'Gamma1': r'\Gamma_1', 'u': r'u', 'rho': r'\rho', 'Y': r'Y', 'psi': r'\psi'} plt.axhspan(0, 0, ls='dashed') latex = (varnames[var1], varnames[var2]) plt.plot(x, R*K1, 'r-', label="$RK_{%s,%s}$"%latex) plt.plot(x, R*K2, 'b-', label="$RK_{%s,%s}$"%latex[::-1]) plt.xlabel(r"r/R") plt.ylabel(r"$RK^{(n,\ell)}$") plt.title(r'Kernel for the $\ell=%d,\;n=%d$ mode'%(l,n)) plt.legend(loc='upper left') #plt.ylim([min(0, min(R*K1), min(R*K2))-0.1, # max(1, max(R*K1), max(R*K2))+0.1]) plt.ylim([-5, 5]) if normalize: plt.xlim([0, 1.01]) else: plt.xlim([0, max(x)]) plt.tight_layout() plt.savefig(os.path.join(output_dir, out_fname+'.png')) plt.close()
def main(): """Create age plot""" d5_domain = np.linspace(0, 2, 100) plt.fill_between(d5_domain, sedov_age(d5_domain, 1, 0.1), sedov_age(d5_domain, 1, 1), label='S-T age, $n_0 \in [0.1, 1]$', color='blue', alpha=0.25) plt.fill_between(d5_domain, tau_age(d5_domain, 0.1), tau_age(d5_domain, 1), label=r'$\tau$ age, $f \in [0.1,1]$', color='red', alpha=0.25) plt.axhspan(st_time_for_arbitrary_density(1, 1.4, 1.0), st_time_for_arbitrary_density(1, 1.4, 0.1), color='black', alpha=0.1) plt.axhline(st_time_for_arbitrary_density(1, 1.4, 1.0), color='black', alpha=0.5) # Mej = 1.4 M_sun, i.e. use M_chandrasekhar. #plt.semilogy(d5_domain, st_time_with_norm_derived_density(d5_domain, 1, 1.4, 1), color='black', ls=':') plt.semilogy(d5_domain, sedov_age(d5_domain, 1, 1), color='blue') plt.semilogy(d5_domain, tau_age(d5_domain, 1), color='red') plt.xlabel(r'Distance $d_{5}$, scaled to 5 kpc') plt.ylabel('Remnant age (yr)') plt.ylim(10, 50000) plt.legend(loc='lower right', frameon=False) plt.tight_layout() plt.savefig('ms/fig_age_plot.pdf') plt.show()
def plplotRaw(x, filename): filename = filename.split('\t')[0] y = [] xu = unique(x) xBin = [] for valu in xu: valb = 0 for val in x: if valu == val: valb +=1 xBin.append(valb) c1 = xu c2 = xBin F = plt.figure(1) h =plt.loglog(c1, c2, 'bo',marker = 'x', markersize=8,markerfacecolor=[1,1,1],markeredgecolor=[0,0,1]) xr1 = pow(10,floor(log(min(x),10))) xr2 = pow(10,ceil(log(min(x),10))) yr2 = max(xBin) plt.axhspan(ymin=0.5,ymax=yr2,xmin=xr1,xmax=xr2) plt.ylabel('Pr(X >= x)',fontsize=12); plt.xlabel('x',fontsize=12) plt.subplots_adjust(left=0.3, bottom=0.3) F.set_size_inches(3,2) F.savefig('visual/plplot%s.pdf' % filename) plt.clf() return h
def draw_plot(self, x_table, y_table, string_number, sound_name, string_target_frequency): fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel('t [s]') ax.set_ylabel('f [Hz]') ax.set_title('Struna '+str((string_number+1))+' do dzwieku '+sound_name) plt.plot(x_table, y_table) ax.set_xlim(0) plt.axhline(y=string_target_frequency) plt.axhspan(string_target_frequency-0.7, string_target_frequency+0.7, xmin=0, facecolor='g', alpha=0.5) data = ('f0 = '+str(round(y_table[0],2))+' Hz\n'+ 'fk = '+str(round(y_table[len(y_table)-1],2))+' Hz\n'+ 'fz = '+str(round(string_target_frequency,2))+' Hz\n'+ 't = '+str(round(x_table[len(x_table)-1]-x_table[0],2))+' s') print data ax.text(0.8, 0.01, data, verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, fontsize=11) plot_name = 'wykres_'+str(string_number)+'.png' plt.savefig(os.path.join('/home/pi/Dyplom/', plot_name)) plt.clf()
def showav(d, fig=1, yps=50, btop=100000, bw=2000): bins = np.arange(0, btop, bw) f = plt.figure(fig) plt.clf() cnds = dconds(d) n = len(cnds) yl = 0 for i, c in enumerate(cnds): sp = plt.subplot(1, n, i + 1) sp.xaxis.set_visible(False) if i > 0: sp.yaxis.set_visible(False) sp.xaxis.set_visible(False) plt.title(c) l = len(d[c]['evts']) for j in range(l): evts = d[c]['evts'][j] if evts: x = np.array(evts) y = np.zeros_like(x) + j plt.plot(x, y, marker='.', color='r', linestyle='None') z = nhplt(flat(d[c]['evts']), bins, color='r', bottom=l + .2 * yps) yl = max(yl, l + 1.3 * yps) if d[c]['avgs']: z = nhplt(flat(d[c]['avgs']), bins, color='b', bottom=l + .1 * yps) if d[c]['dj']: for j in range(l): evts = d[c]['dj'][j] if evts: x = np.array(evts) y = np.zeros_like(x) + j plt.plot(x, y, marker='.', color='g', linestyle='None') z = nhplt(flat(d[c]['dj']), bins, color='g', bottom=l + .1 * yps) if d[c]['avg'] != None: avl = int(l / 2.0) if len(d[c]['avg']) == 0: plt.axhspan(avl, avl + 1, color='b') else: x = np.array(d[c]['avg']) y = np.zeros_like(x) + avl plt.plot(x, y, marker='o', color='b', markersize=10.0, linestyle='None') if d[c]['avgvar'] != None: av = d[c]['avgvar'] a = [0] + list(x) + [max(flat(d[c]['evts']))] nx = [(a[i] + a[i - 1]) / 2.0 for i in range(1, len(a))] ny = np.zeros_like(nx) + avl ye = ([0] * len(av), [v[4] * yps for v in av]) plt.errorbar(nx, ny, yerr=ye, color='k', marker='.', markersize=4.0, linestyle='None', elinewidth=3) av = av[:-1] xmc = np.array([v[1] for v in av]) xe = [v[2] for v in av] ymc = np.array([v[3] * yps for v in av]) plt.errorbar(x + xmc, y + ymc, xerr=xe, marker='s', color='b', markersize=6.0, linestyle='None', elinewidth=3) for i in range(len(cnds)): sp = plt.subplot(1, n, i + 1) plt.ylim([0, yl]) f.canvas.draw()
def plotAvgHist(column, field, bins=40): global subplot subplot +=1 plt.subplot(subplot) plt.title( '%s: \nmean=%s std=%s ' % (field, round(mean(column), 3), round(std(column), 3)), fontsize=11 ) plt.axhspan(0, 2000, color='none') plt.hist( column, bins=bins, range=(0,1)) print '%s: mean=%s std=%s items_under_0.3=%s' % (field, round(mean(column), 3), round(std(column), 3), sum([1 for c in column if c<0.3]) )
def plot_graph(): """ Plots a graph with specs listed below :return: a nice matplotlib graph """ # sets the parametres of the graph to be plotted fig, ax = plt.subplots() # Plots the actual graph out of the above lists stock_line = plt.plot(datetime_list, monthly_prices, color='#33CCFF', linewidth=3.0, linestyle='-') # Demarcates the fields of best and worst performing months plt.axhspan(ymin=min(best_stock_prices), ymax=max(best_stock_prices), xmin=0, xmax=1, color='#99CC00') green_best = mpatches.Patch(color='#99CC00') plt.axhspan(ymin=min(worst_stock_prices), ymax=max(worst_stock_prices), xmin=0, xmax=1, color='#FF0066') red_worst = mpatches.Patch(color='#FF0066') # all the labelling, ticks based on dates, and some style stuff ax.set_title(stock_title + '\nHistorical Monthly Prices') ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_ylabel("$\$$ USD") ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) # makes sure the x axis is is as long as the data datemin = min(datetime_list) datemax = max(datetime_list) ax.set_xlim(datemin, datemax) box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9]) # Put a legend below current axis ax.legend([green_best, red_worst], ['Best Months', 'Worst Months'], loc=9, bbox_to_anchor=(0.5, -0.1), ncol=3) # sets the display parametres for mouseover (x = time, y = price) def price(x): return '$%1.2f'% x ax.format_xdata = mdates.DateFormatter('%Y/%m') ax.format_ydata = price ax.grid(True) fig.autofmt_xdate() fig.savefig('bonus_02_visual.png') plt.show()
def plot_scatter(table, labels, k): markers = ['o', 'x', '^', '*', 's'] print len(table), len(labels) tab = np.column_stack((np.array(table), np.array(labels))) # np.random.shuffle(tab) # tab = tab[:50000] # plt.ioff() # # plt.plot(tab[:,0], tab[:,1], markers[0]) # # # y1 = sorted([x[1] for x in tab if x[0] < 0.5]) # y2 = sorted([x[1] for x in tab if x[0] >= 0.5]) # # n = len(y1) # # plt.axhspan(0, y2[n/3], 0.5, 1, hold=None, fill=False) # plt.axhspan(y2[n/3], y2[2*n/3], 0.5, 1, hold=None, fill=False) # plt.axhspan(y2[2*n/3], 1.0, 0.5, 1, hold=None, fill=False) # # plt.axhspan(0, y1[n/3], 0, 0.5, hold=None, fill=False) # plt.axhspan(y1[n/3], y1[2*n/3], 0, 0.5, hold=None, fill=False) # plt.axhspan(y1[2*n/3], 1.0, 0, 0.5, hold=None, fill=False) # # # for x in range(l): # for y in range(w): # plt.axhspan(y*1.0/w, (y+1.0)/w, (x*1.0)/l, (x+1.0)/l, hold=None, fill=False) for it in range(k): sub_tab = np.array([np.array(row) for row in tab if int(row[-1]) == int(it)]) plt.plot(sub_tab[:,0], sub_tab[:,1], markers[it%5]) xmin = 2 ymin = 2 xmax = -1 ymax = -1 for row in sub_tab: if row[0] < xmin: xmin = row[0] if row[0] > xmax: xmax = row[0] if row[1] < ymin: ymin = row[1] if row[1] > ymax: ymax = row[1] plt.axhspan(ymin, ymax, xmin, xmax, hold=None, fill=False) plt.show()
def plot_palette(pa, title=None, xlabel=None, y=None, show_regions=False, show_primary_haps=False, pair_gap=0, linewidth=6, snp_range=None, colors=None): '''Generate a haplotype coloring plot from coloring palette pa.''' # Generate haplotype colors haps, regions, c = pa.haps, pa.regions, pa.color colors = colors if colors is not None else list(it.islice(im.plot.colors.get_colors(), pa.num_colors)) # Last color: always gray colors[-1] = (0.4, 0.4, 0.4) # Prepare axes num_haps = len(haps) y = y if y is not None else map(repr, haps) xmin, xmax = regions[0][START], regions[-1][STOP] x_scaled = lambda x: (1.0 * (x - xmin)) / (xmax - xmin) P.clf() P.hold(True) if title is not None: P.title(title) P.xlim([xmin, xmax]) P.xlabel(xlabel if xlabel else 'SNP #') P.ylabel('Sample') hap_ticks = np.arange(0, num_haps) if pair_gap > 0: hap_ticks += np.array(list(it.chain.from_iterable(map(lambda x: (x, x), xrange(num_haps / 2))))) P.yticks(hap_ticks, y) ymin, ymax = hap_ticks[0] - 0.5, hap_ticks[-1] + 0.5 P.ylim([ymin, ymax]) # Show region boundaries in dashed lines if show_regions: boundaries = sorted(set([y for x in pa.regions for y in x])) print boundaries for k, boundary in enumerate(boundaries[1:], 1): P.axvline(x=boundary, linestyle='dotted', linewidth=1, color='k') P.text(0.5 * (boundaries[k - 1] + boundaries[k]), hap_ticks[0] - 0.4, '%d' % (k - 1,)) # Draw each segment in its corresponding color for i, j in it.product(xrange(pa.num_haps), xrange(pa.num_regions)): # Draw lines for all members of the group using the same color # print '[%d,%d] x %.2f:%.2f y=%.2f color %d' % (regions[j][START], regions[j][STOP], x_scaled(regions[j][START]), x_scaled(regions[j][STOP]), hap_ticks[i], c[i, j]) P.axhspan(xmin=x_scaled(regions[j][START]), xmax=x_scaled(regions[j][STOP]), ymin=hap_ticks[i] - 0.5 * linewidth, ymax=hap_ticks[i] + 0.5 * linewidth, color=colors[c[i, j]]) # Draw where primary haplotypes have been identified if show_primary_haps: primary = pa.color_sequence() for k, seq in enumerate(primary): for i, j in seq: P.axhspan(xmin=x_scaled(regions[j][START]), xmax=x_scaled(regions[j][STOP]), ymin=hap_ticks[i] + 0.9 * linewidth, ymax=hap_ticks[i] + 1.1 * linewidth, color=colors[k]) P.show()
def test_axhspan_epoch(): from datetime import datetime import matplotlib.testing.jpl_units as units units.register() t0 = units.Epoch( "ET", dt=datetime(2009, 1, 20) ) tf = units.Epoch( "ET", dt=datetime(2009, 1, 21) ) dt = units.Duration( "ET", units.day.convert( "sec" ) ) fig = plt.figure() plt.axhspan( t0, tf, facecolor="blue", alpha=0.25 ) ax = plt.gca() ax.set_ylim( t0 - 5.0*dt, tf + 5.0*dt ) fig.savefig( 'axhspan_epoch' )
def main(): z = np.arange(-7, 7, 0.1) phi_z = sigmoid(z) plt.plot(z, phi_z) plt.axvline(0.0, color='k') plt.axhspan(0.0, 1.0, facecolor='1.0', alpha=1.0, ls='dotted') plt.axhline(y=0.5, ls='dotted', color='k') plt.yticks([0.0, 0.5, 1.0]) plt.ylim(-0.1, 1.1) plt.xlabel('z') plt.ylabel('$\phi (z)$') plt.show()
def plot(self, win=None, newfig=True, figsize=None, orientation='hor', topfigfrac=0.8): """Plot layout Parameters ---------- win : list or tuple [x1, x2, y1, y2] """ if newfig: plt.figure(figsize=figsize) ax1 = None ax2 = None if orientation == 'both': ax1 = plt.axes([0.125, 0.18 + (1 - topfigfrac) * 0.7, (0.9 - 0.125), topfigfrac * 0.7]) ax2 = plt.axes([0.125, 0.11, (0.9 - 0.125), (1 - topfigfrac) * 0.7], sharex=ax1) elif orientation[:3] == 'hor': ax1 = plt.subplot() elif orientation[:3] == 'ver': ax2 = plt.subplot() else: if orientation == 'both': fig = plt.gcf() ax1 = fig.axes[0] ax2 = fig.axes[1] elif orientation[:3] == 'hor': fig = plt.gcf() ax1 = fig.axes[0] ax2 = None elif orientation[:3] == 'ver': fig = plt.gcf() ax1 = None ax2 = fig.axes[0] if ax1 is not None: plt.sca(ax1) for e in self.elementlist: e.plot() if orientation[:3] == 'hor': plt.axis('scaled') elif orientation == 'both': plt.axis('equal') # cannot be 'scaled' when sharing axes if win is not None: plt.axis(win) if ax2 is not None: plt.sca(ax2) for i in range(self.aq.nlayers): if self.aq.ltype[i] == 'l': plt.axhspan(ymin=self.aq.z[i + 1], ymax=self.aq.z[i], color=[0.8, 0.8, 0.8]) for i in range(1, self.aq.nlayers): if self.aq.ltype[i] == 'a' and self.aq.ltype[i - 1] == 'a': plt.axhspan(ymin=self.aq.z[i], ymax=self.aq.z[i], color=[0.8, 0.8, 0.8])
def instrumentalness(): global esn, visualiser train_skip = sys.argv[1] test_skip = sys.argv[2] pkl = sys.argv[3] if len(sys.argv) > 3 else None n_forget_points = 0 train_input, train_output, train_splits, test_input, test_output, test_splits, esn = test_data.instrumentalness() visualiser = Visualiser(esn, output_yscale=.3) if pkl: with open(pkl) as f: esn.unserialize(cPickle.load(f)) else: esn.train(train_input, train_output, callback=refresh, n_forget_points=n_forget_points, callback_every=int(train_skip), reset_points=train_splits) visualiser.set_weights() esn.reset_state() esn.noise_level = 0 #test_input, test_output, test_splits = train_input, train_output, train_splits import ipdb; ipdb.set_trace() print 'test' estimated_output = esn.test(test_input, n_forget_points=n_forget_points, callback_every=int(test_skip), callback=refresh, reset_points=test_splits, actual_output=test_output * esn.teacher_scaling + esn.teacher_shift) error = nrmse(estimated_output, test_output) print 'error: %s' % error means = [] estimated_means = [] for start, end in zip(test_splits[:-1], test_splits[1:]): means.append(np.mean(test_output[start:end])) estimated_means.append(np.mean(estimated_output[start:end])) plt.plot(means, 'go', markersize=10) plt.plot(estimated_means, 'r*', markersize=10) for i, (out, est) in enumerate(zip(means, estimated_means)): if out > est: col = 'c' else: col = 'y' i /= float(len(means)) plt.axhspan(out, est, i - .005, i + 0.005, color=col) plt.show()
def plot_2D(self, file_name, var1, var2, nbins1, nbins2, xmin1, xmax1, xmin2, xmax2, **kwargs): vals1 = [] wgts = [] vals2 = [] cuts = kwargs.get('cuts', '(True)') title = kwargs.get('title', '') xlab = kwargs.get('xlab','') ylab = kwargs.get('ylab','') cut = "%s & %s" % (self.base_selections, cuts) for mc in self.sample_order: self.log.info("Processing MC: %s" % mc) for sample_name in self.sample_groups[mc]["sample_names"]: with tb.open_file("%s/%s.h5" % (self.ntuple_dir, sample_name), 'r') as h5file: for chan in self.channels: table = getattr(getattr(h5file.root, self.analysis), chan) vals1 += [x[var1] for x in table.where(cut)] vals2 += [x[var2] for x in table.where(cut)] scale = self.lumi * xsec.xsecs[sample_name] / \ xsec.nevents[sample_name] wgts += [x['pu_weight'] * x['lep_scale'] * \ scale for x in table.where(cut)] plt.figure(figsize=(6, 5)) (n, xbins, ybins, Image) = plt.hist2d( vals1, vals2, bins=[nbins1,nbins2], range=[[xmin1,xmax1],[xmin2,xmax2]], weights=wgts) plt.colorbar() plt.title(title) plt.xlabel(xlab, ha='right', position=(1,0), size='larger') plt.ylabel(ylab, ha='right', position=(0,1), size='larger') plt.axhspan(450,550,0.375,0.625,fill=False,edgecolor='white') plt.tight_layout(0.5) self.log.info("Generating Histogram: %s:%s, %s/%s" % (var1,var2, self.out_dir, file_name)) plt.savefig("%s/%s" % (self.out_dir, file_name)) plt.clf()
def vitals_bp(request, id): """ """ from ocemr.models import Patient, VitalType, Vital p = Patient.objects.get(pk=id) vt_bpS= VitalType.objects.get(title="BP - Systolic") v_bpS=Vital.objects.filter(patient=p,type=vt_bpS) bpS_date_list=[] bpS_data_list=[] for v in v_bpS: bpS_date_list.append(v.observedDateTime) bpS_data_list.append(v.data) vt_bpD= VitalType.objects.get(title="BP - Diastolic") v_bpD=Vital.objects.filter(patient=p,type=vt_bpD) bpD_date_list=[] bpD_data_list=[] for v in v_bpD: bpD_date_list.append(v.observedDateTime) bpD_data_list.append(v.data) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,5),dpi=75) fig.interactive = False plt.title('Blood Pressure History for %s'%(p)) plt.grid(True) plt.axhspan(ymin=90, ymax=140, color='b',alpha=.2) plt.axhspan(ymin=60, ymax=90, color='g',alpha=.2) plt.axhline(y=120, color='b') plt.axhline(y=80, color='g') plt.plot(bpS_date_list, bpS_data_list, 'o-', color='r', label="systolic") plt.plot(bpD_date_list, bpD_data_list, 'o-', color='m', label="diastolic") plt.ylabel('mmHg') plt.legend(loc=0) fig.autofmt_xdate() fig.text(0.15, 0.33, 'OCEMR', fontsize=150, color='gray', alpha=0.07) plt.draw() canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig) response = HttpResponse(content_type='image/png') canvas.print_png(response) plt.close(fig) return response
def plotTimeline(a, filename): # Converts str into a datetime object. conv = lambda s: dt.datetime.strptime(s, '%H:%M:%S:%f') # Use numpy to read the data in. data = np.genfromtxt(a, converters={1: conv, 2: conv}, \ names=['caption', 'start', 'stop', 'state'], \ dtype=None, delimiter=",") cap, start, stop = data['caption'], data['start'], data['stop'] # Check the status, because we paint all lines with the same color # together is_ok = (data['state'] == 'OK') not_ok = np.logical_not(is_ok) # Get unique captions and there indices and the inverse mapping captions, unique_idx, caption_inv = np.unique(cap, 1, 1) # Build y values from the number of unique captions. y = (caption_inv + 1) / float(len(captions) + 1) # Plot ok tl black timelines(y[is_ok], start[is_ok], stop[is_ok], 'k') # Plot fail tl red timelines(y[not_ok], start[not_ok], stop[not_ok], 'r') # Setup the plot ax = plt.gca() fig = ax.get_figure() fig.set_figheight(6) fig.set_figwidth(18) ax.xaxis_date() myFmt = DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(myFmt) ax.xaxis.set_major_locator(SecondLocator(interval=10)) # used to be SecondLocator(0, interval=20) plt.axhspan(0.19, 1, facecolor='0.8', alpha=0.5) # To adjust the xlimits a timedelta is needed. delta = (stop.max() - start.min())/10 plt.yticks(y[unique_idx], captions, size=14) # plt.ylim(0,1) plt.tight_layout() plt.gcf().subplots_adjust(bottom=0.1) plt.xticks(size = 14) plt.xlim(start.min()-delta, stop.max()+delta) plt.xlabel('Timeline', size=17) plt.savefig(filename, format='eps', dpi=200)
def viz_csv(rmn_traj, rmn_descs, min_length=10, smallest_shift=1, max_viz=False, fig_dir=None): for book in rmn_traj: for rel in rmn_traj[book]: rtraj = rmn_traj[book][rel] if len(rtraj) > min_length and len(rtraj)<150: print book, rel plt.close() rtraj_mat = array(rtraj) if max_viz: plt.title(book + ': ' + rel) plt.axis('off') max_rtraj = argmax(rtraj_mat, axis=1) rcenter_inds = compute_centers(max_rtraj, smallest_shift) for ind in range(0, len(max_rtraj)): topic = max_rtraj[ind] plt.axhspan(ind, ind+1, 0.2, 0.4, color=color_list[topic]) if ind in rcenter_inds: loc = (0.43, ind + 0.5) plt.annotate(rmn_descs[topic], loc, size=15, verticalalignment='center', color=color_list[topic]) plt.xlim(0, 1.0) plt.arrow(0.1,0,0.0,len(rtraj), head_width=0.1, head_length=len(rtraj)/12, lw=3, length_includes_head=True, fc='k', ec='k') props = {'ha': 'left', 'va': 'bottom',} plt.text(0.0, len(rtraj) / 2, 'TIME', props, rotation=90, size=15) props = {'ha': 'left', 'va': 'top',} if fig_dir is None: plt.show() else: chars = rel.split(' AND ') fig_name = fig_dir + book + \ '__' + chars[0] + '__' + chars[1] + '.png' print 'figname = ', fig_name plt.savefig(fig_name)
def comparing_humi_temps_from_dataframe_by_day(dataframe_thermo, dataframe_SHT1x, string_day, temp_param_MAX, temp_param_MIN, temp_MAX, temp_MIN, temp_limit_SUP, temp_limit_INF, humi_limit_SUP, humi_limit_INF): f, axarr = plt.subplots(2, sharex=True) # First subplot plt.subplot(2, 1, 1) today_plot_thermo = dataframe_thermo.TEMP_LOG[string_day] plt.ylim(temp_limit_INF, temp_limit_SUP) y=np.arange(temp_limit_INF, temp_limit_SUP, 0.2) plt.grid() plt.yticks(y) today_plot_thermo.plot() plt.axhspan(temp_param_MIN, temp_param_MAX, facecolor='g', alpha=0.2) plt.axhspan(temp_MIN, temp_MAX, facecolor='g', alpha=0.2) plt.ylabel('Temperature (C)') plt.xlabel('') # Second subplot plt.subplot(2, 1, 2) today_plot_SHT1x_humi = dataframe_SHT1x.humi[string_day] today_plot_SHT1x_temp = dataframe_SHT1x.temp[string_day] plt.ylim(humi_limit_INF, humi_limit_SUP) plt.grid() today_plot_SHT1x_humi.plot() plt.axhspan(humi_param_MIN, humi_param_MAX, facecolor='g', alpha=0.2) plt.axhspan(humi_MIN, humi_MAX, facecolor='g', alpha=0.2) plt.ylabel('Humidity (%)') plt.xlabel('Hours') # Pearson correlation: http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient # 0 implies that there is no linear correlation between the variables. pearson_corr_index = today_plot_SHT1x_temp.corr(today_plot_SHT1x_humi) plt.suptitle('Correlation between temperature and humidity\n') plt.suptitle('\n\nCalculated Pearson correlation index: %.2f' % pearson_corr_index, color='b') plt.savefig('static/data/comparing_humi_temps_%s.png' % string_day, orientation='landscape') plt.close()
def bestResponseAsAfunctionOfCostAndPrx(): #plot best response variation as function of I+N and cost player = Player(10001, 25, 2, 1000.00, player_number=1, game_Type=0) #give the node id which cause interference to player tx2_node_id = 16 #I want to determine the maximum level of interference #average direct gain hii = GainCalculations.getAverageGain(player.coordinator_id, player.tx_node.node_id, player.rx_node.node_id, year=2013, month=8, day=23) #maximum cross gain hji = GainCalculations.getMinMaxGain(10001, tx2_node_id, player.rx_node.node_id, year=2013, month=8, day=24) #get average noise noise = GainCalculations.getAverageNoise(player.coordinator_id, player.tx_node.node_id, player.rx_node.node_id, year=2013, month=8, day=23) max_interference_and_noise = 0.001*hji[1] + noise max_interference_and_noise = 10.00*math.log10(max_interference_and_noise/0.001) interference_and_noise = numpy.arange(max_interference_and_noise, max_interference_and_noise-10, -2) cost = numpy.arange(100, 10000, 0.1) #now plot results plot.ioff() plot.clf() plot.grid() plot.title("B%d (c%d, I+N)" %(player.player_number, player.player_number)) plot.xlabel("c%d" %(player.player_number)) plot.ylabel("B%d [dBm]" %(player.player_number)) for i in interference_and_noise: tmp_list = [] tmp_cost = [] for c in cost: tmp_bi = getBi(c, math.pow(10.00, i/10.00)*0.001, 10.00*math.log10(hii)) if tmp_bi!=None: tmp_list.append(tmp_bi) tmp_cost.append(c) plot.plot(tmp_cost, tmp_list, label = "I+N=%.1f dBm" %i) plot.plot([],[],label = "h%d%d = %.3f dB" %(player.player_number, player.player_number, 10.00*math.log10(hii))) plot.axhspan(-55, 0, alpha = 0.1) plot.legend(bbox_to_anchor=(1.05, 1.05)) plot.show() #bestResponseAsAfunctionOfCostAndPrx() #bestResponseAsAFunctionOfDirectGain() #bestResponseAsAFunctionOfRx()
def agdd_plots(nplots, iplot, tbase, tmax, t_range, temp, agdd): """This function does the AGDD plots in a nplots vertical stack of plots. iplot is the current plot (from top to bottom, starting at 1), tbase and tmax are the values used for AGDD calculations. t_range is a temporal range (usually DoY) and temp and AGDD are extracted 2m temperature and AGDD""" plt.subplot(nplots, 1, iplot) # Put a grey area for the AGDD calculation bounds plt.axhspan(tbase, tmax, xmin=0, xmax=366, color="0.9") # Plot temperature plt.plot(t_range, temp, "-r", label="Tm") plt.ylabel("Mean Temp [degC]") plt.grid(True) plt.twinx() plt.plot(t_range, agdd, "-g", label="AGDD") plt.ylabel("AGDD [degC]")
def plot(self,timeFrameToAlphabetListSorted): for price in timeFrameToAlphabetListSorted: alphabetList=timeFrameToAlphabetListSorted[price] alphabet = r' '.join(alphabetList) plt.yticks(range(self.minY, self.maxY)) plt.xticks(range(self.minX, self.maxX)) txt = self.ax.text(self.currentDay, price, alphabet, fontsize=10) mng = plt.get_current_fig_manager() mng.resize(*mng.window.maxsize()) totalSizeOfDictionary=len(timeFrameToAlphabetListSorted) if totalSizeOfDictionary >1: minVal=timeFrameToAlphabetListSorted.keys()[0] maxVal=timeFrameToAlphabetListSorted.keys()[totalSizeOfDictionary-1] plt.axhspan(ymin=minVal-1,ymax=maxVal,xmin=0, xmax=1,facecolor='0.5', alpha=0.5) plt.draw() plt.pause(0.001)
def vitals_hrrr(request, id): """ """ from ocemr.models import Patient, VitalType, Vital p = Patient.objects.get(pk=id) vt_hr = VitalType.objects.get(title="HR") v_hr = Vital.objects.filter(patient=p, type=vt_hr) hr_date_list = [] hr_data_list = [] for v in v_hr: hr_date_list.append(v.observedDateTime) hr_data_list.append(v.data) vt_rr = VitalType.objects.get(title="RR") v_rr = Vital.objects.filter(patient=p, type=vt_rr) rr_date_list = [] rr_data_list = [] for v in v_rr: rr_date_list.append(v.observedDateTime) rr_data_list.append(v.data) import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt fig = plt.figure(num=1, figsize=(10, 5), dpi=75) fig.interactive = False plt.title("Heart / Resp Rate History for %s" % (p)) plt.grid(True) plt.axhspan(ymin=60, ymax=80, color="b", alpha=0.33) plt.axhspan(ymin=10, ymax=20, color="g", alpha=0.33) plt.axhline(y=12, color="g") plt.plot(hr_date_list, hr_data_list, "o-", color="r", label="Heart") plt.plot(rr_date_list, rr_data_list, "o-", color="m", label="Resp") plt.ylabel("rate (bpm)") l = plt.legend(loc=0) fig.autofmt_xdate() fig.text(0.15, 0.33, "OCEMR", fontsize=150, color="gray", alpha=0.07) plt.draw() canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig) response = HttpResponse(content_type="image/png") canvas.print_png(response) matplotlib.pyplot.close(fig) return response
def __init__(self, *args, **kwargs): import matplotlib as mpl import matplotlib.pyplot as plt from collections import deque kwargs["gui"] = True super(tqdm_gui, self).__init__(*args, **kwargs) # Initialize the GUI display if self.disable or not kwargs["gui"]: return self.fp.write("Warning: GUI is experimental/alpha\n") self.mpl = mpl self.plt = plt self.sp = None # Remember if external environment uses toolbars self.toolbar = self.mpl.rcParams["toolbar"] self.mpl.rcParams["toolbar"] = "None" self.mininterval = max(self.mininterval, 0.5) self.fig, ax = plt.subplots(figsize=(9, 2.2)) # self.fig.subplots_adjust(bottom=0.2) if self.total: self.xdata = [] self.ydata = [] self.zdata = [] else: self.xdata = deque([]) self.ydata = deque([]) self.zdata = deque([]) self.line1, = ax.plot(self.xdata, self.ydata, color="b") self.line2, = ax.plot(self.xdata, self.zdata, color="k") ax.set_ylim(0, 0.001) if self.total: ax.set_xlim(0, 100) ax.set_xlabel("percent") self.fig.legend((self.line1, self.line2), ("cur", "est"), loc="center right") # progressbar self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color="g") else: # ax.set_xlim(-60, 0) ax.set_xlim(0, 60) ax.invert_xaxis() ax.set_xlabel("seconds") ax.legend(("cur", "est"), loc="lower left") ax.grid() # ax.set_xlabel('seconds') ax.set_ylabel((self.unit if self.unit else "it") + "/s") if self.unit_scale: plt.ticklabel_format(style="sci", axis="y", scilimits=(0, 0)) ax.yaxis.get_offset_text().set_x(-0.15) # Remember if external environment is interactive self.wasion = plt.isinteractive() plt.ion() self.ax = ax
def test_axhspan_epoch(): from datetime import datetime import matplotlib.testing.jpl_units as units units.register() # generate some data t0 = units.Epoch("ET", dt=datetime(2009, 1, 20)) tf = units.Epoch("ET", dt=datetime(2009, 1, 21)) dt = units.Duration("ET", units.day.convert("sec")) fig = plt.figure() plt.axhspan(t0, tf, facecolor="blue", alpha=0.25) ax = plt.gca() ax.set_ylim(t0 - 5.0 * dt, tf + 5.0 * dt)
def shade(ax, region=[None, None, None, None]): """ Shade a rectangular region specified """ if region == [None, None, None, None]: return else: raise Exception("FINISH") p = plt.axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)
def plot_rating_bg(ranks): ymin, ymax = plt.gca().get_ylim() bgcolor = plt.gca().get_facecolor() for rank in ranks: plt.axhspan( rank.low, rank.high, facecolor=rank.color_graph, alpha=0.8, edgecolor=bgcolor, linewidth=0.5, ) locs, labels = plt.xticks() for loc in locs: plt.axvline(loc, color=bgcolor, linewidth=0.5) plt.ylim(ymin, ymax)
def comparing_temps_from_dataframe_by_day(dataframe_thermo, dataframe_SHT1x, string_day, temp_param_MAX, temp_param_MIN, temp_MAX, temp_MIN, temp_limit_SUP, temp_limit_INF): plt.title('Comparation of the temperatures of day %s' % string_day) today_plot_thermo = dataframe_thermo.TEMP_LOG[string_day] today_plot_SHT1x = dataframe_SHT1x.temp[string_day] plt.ylim(temp_limit_INF, temp_limit_SUP) y=np.arange(temp_limit_INF, temp_limit_SUP, 0.2) plt.grid() plt.yticks(y) today_plot_thermo.plot() today_plot_SHT1x.plot() plt.axhspan(temp_param_MIN, temp_param_MAX, facecolor='g', alpha=0.2) plt.axhspan(temp_MIN, temp_MAX, facecolor='g', alpha=0.2) legend( ('thermo', 'SHT1x', 'Recommended zone') , loc = 'upper right') plt.ylabel('Temperature (%sC)' % degree_sign) plt.xlabel('Hours') plt.savefig('static/data/comparing_temps_%s.png' % string_day, orientation='landscape') plt.close()
def vitals_temp(request, id): """ """ from ocemr.models import Patient, VitalType, Vital p = Patient.objects.get(pk=id) vt_temp = VitalType.objects.get(title="Temp") v_temp = Vital.objects.filter(patient=p, type=vt_temp) temp_date_list = [] temp_data_list = [] for v in v_temp: temp_date_list.append(v.observedDateTime) temp_data_list.append(v.data) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig = plt.figure(num=1, figsize=(10, 5), dpi=75) fig.interactive = False plt.title('Temperature History for %s' % (p)) plt.grid(True) plt.axhspan(ymin=36.3, ymax=37.3, color='g', alpha=.5) plt.axhline(y=37, color='g') plt.plot(temp_date_list, temp_data_list, 'o-', color='r', label="Temp") plt.ylabel('degrees C') plt.legend(loc=0) try: plt.xlim( matplotlib.dates.date2num(min(temp_date_list)) - 1, matplotlib.dates.date2num(max(temp_date_list)) + 1, ) except ValueError: pass fig.autofmt_xdate() fig.text(0.15, 0.33, 'OCEMR', fontsize=150, color='gray', alpha=0.07) plt.draw() canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig) import StringIO output = StringIO.StringIO() canvas.print_png(output, format='png') response = HttpResponse(output.getvalue(), content_type='image/png') matplotlib.pyplot.close(fig) return response
def display_DDC(self): plt.close('all') plt.figure(1) plt.plot(self.ECD.calcul_DDCS()[0], self.ECD.calcul_DDCS()[1], "g-o") plt.plot(self.ECD.calcul_DDCD()[0], self.ECD.calcul_DDCD()[1], "r-x") plt.xlabel('Vce (V)') plt.ylabel('Ic (A)') plt.title('Droite de charge') plt.legend(["Statique", "Dynamique"]) plt.grid() plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) plt.annotate(s="Point de polarisation", xy=(self.ECD.Vceq, self.ECD.Icq)) plt.annotate(s="Icmax: {:.2e}".format(self.ECD.calcul_DDCS()[1][0]), xy=(self.ECD.calcul_DDCS()[0][0], self.ECD.calcul_DDCS()[1][0])) plt.annotate(s="icmax: {:.2e}".format(self.ECD.calcul_DDCD()[1][0]), xy=(self.ECD.calcul_DDCD()[0][0], self.ECD.calcul_DDCD()[1][0])) plt.annotate( s="vcemax: {}".format(round(self.ECD.calcul_DDCD()[0][2], 2)), xy=(self.ECD.calcul_DDCD()[0][2], self.ECD.calcul_DDCD()[1][2])) xmin, xmax, ymin, ymax = self.ECD.calcul_dynamic_limits() plt.axvspan(xmin, xmax, ymin=0, ymax=1, alpha=0.2) plt.axvline(xmin, linestyle="dotted") plt.axvline(xmax, linestyle="dotted") plt.axhspan(ymin, ymax, xmin=0, xmax=1, alpha=0.2, facecolor='g') plt.axhline(ymin, linestyle="dotted", color='g') plt.axhline(ymax, linestyle="dotted", color='g') plt.annotate("", xy=(xmin, ymin), xytext=(xmin, ymax), arrowprops=dict(arrowstyle="<->")) plt.annotate("Δic", xy=(0, 0), xytext=(xmin, self.ECD.Icq)) plt.annotate("", xy=(xmin, ymin), xytext=(xmax, ymin), arrowprops=dict(arrowstyle="<->")) plt.annotate("Δvce", xy=(0, 0), xytext=(self.ECD.Vceq, ymin)) plt.show() pass
def main(inargs): """Run the program.""" df = pd.read_csv(inargs.infile) df.set_index(df['model'], drop=True, inplace=True) #df.set_index(df['model'] + ' (' + df['run'] + ')', drop=True, inplace=True) x = np.arange(df.shape[0]) ncmip5 = df['project'].value_counts()['cmip5'] df_ohc = df[[ 'OHC (J yr-1)', 'thermal OHC (J yr-1)', 'barystatic OHC (J yr-1)' ]] sec_in_year = 365.25 * 24 * 60 * 60 earth_surface_area = 5.1e14 df_ohc = (df_ohc / sec_in_year) / earth_surface_area df_ohc = df_ohc.rename( columns={ "OHC (J yr-1)": "change in OHC ($dH/dt$)", "thermal OHC (J yr-1)": "change in OHC temperature component ($dH_T/dt$)", "barystatic OHC (J yr-1)": "change in OHC barystatic component ($dH_m/dt$)" }) df_ohc.plot.bar(figsize=(18, 6), color=['#272727', 'tab:red', 'tab:blue'], width=0.9, zorder=2) plt.axhspan(0.4, 1.0, color='0.95', zorder=1) plt.axvline(x=ncmip5 - 0.5, color='0.5', linewidth=2.0) units = 'equivalent planetary energy imbalance (W m$^{-2}$)' plt.ylabel(units) plt.axvline(x=x[0] - 0.5, color='0.5', linewidth=0.1) for val in x: plt.axvline(x=val + 0.5, color='0.5', linewidth=0.1) quartiles = get_quartiles(df_ohc, "change in OHC ($dH/dt$)", df['project'], units) plt.savefig(inargs.outfile, bbox_inches='tight', dpi=400) log_file = re.sub('.png', '.met', inargs.outfile) log_text = cmdprov.new_log(git_repo=repo_dir, extra_notes=quartiles) cmdprov.write_log(log_file, log_text)
def plt_sigmoid(data, w): # 其拟合方程形式为f(x)=w0+w1*x1+w2*x2.... # 生成两个矩阵 data = np.mat(data) w = np.array(w) z = data * np.transpose(w) # 矩阵转置,相乘后得到z值 z.sort(axis=0) # 画sigmoid函数 phi_z = sigmoid(z) plt.plot(z, phi_z) plt.axvline(0.0, color='k') plt.axhspan(0.0, 1.0, facecolor='1.0', alpha=1.0, ls='dotted') plt.yticks([0.0, 0.5, 1.0]) plt.ylim(-0.1, 1.1) plt.xlabel('z') plt.ylabel('$\phi (z)$') plt.show()
def graph_w_T(t, catal): plt.gca().invert_yaxis() plt.title('Well temperature,K time = ' + str(t) + 's') plt.xlabel('T, K') plt.ylabel('depth, m') plt.grid(color='gray', linestyle='dashed') plast_cout = len(plast.ht) for j in range(plast_cout): plt.axhspan(float(plast.ht[j]), float(plast.hb[j]), facecolor='0.5', alpha=0.5) plt.plot(well.Tgeo, well.z, label='geotherm') plt.plot(well.T, well.z, label='well temper') plt.legend() plt.savefig(catal + '/' + 'Temp-well_' + str(t) + '.png') plt.draw() plt.close()
def quartile_bins_viz(data, column, ylabel, title, figsize=(15, 8)): """Visualize quartile bins.""" ax = data.plot(y=column, figsize=figsize, color='black', title=title) xlims = ax.get_xlim() for bin_name, hatch, bounds in zip( [r'$Q_1$', r'$Q_2$', r'$Q_3$', r'$Q_4$'], ['\\\\\\', '', '///', '||||'], pd.qcut(data.volume, q=4).unique().categories.values ): plt.axhspan(bounds.left, bounds.right, alpha=0.2, label=bin_name, hatch=hatch, color='black') plt.annotate(f' {bin_name}', xy=(xlims[0], (bounds.left + bounds.right) / 2.1), fontsize=11) ax.set(xlabel='', ylabel=ylabel) plt.legend(bbox_to_anchor=(1, 0.67), frameon=False, fontsize=14) return ax
def low_med_high_bins_viz(data, column, ylabel, title, figsize=(15, 3)): """Visualize the low, medium, and high equal-width bins.""" ax = data.plot(y=column, figsize=figsize, color='black', title=title) xlims = ax.get_xlim() for bin_name, hatch, bounds in zip( ['low', 'med', 'high'], ['///', '', '\\\\\\'], pd.cut(data[column], bins=3).unique().categories.values ): plt.axhspan(bounds.left, bounds.right, alpha=0.2, label=bin_name, hatch=hatch, color='black') plt.annotate(f' {bin_name}', xy=(xlims[0], (bounds.left + bounds.right) / 2.1), ha='left') ax.set(xlabel='', ylabel=ylabel) plt.legend(bbox_to_anchor=(1, 0.75), frameon=False) return ax
def decorate_plot(self, hconst=None, vconst=None): """Decorate the plot with an optional horizontal and vertical constant """ # Plotting an additional constant if isinstance(hconst, (np.ndarray, list, tuple)): plt.axhline(hconst[0], color='#b58900') plt.text(X[0], hconst[0] + X[0] / 100., label[5]) plt.axhspan(hconst[0] + hconst[1], hconst[0] - hconst[1], alpha=0.35, color='gray') if isinstance(vconst, (np.ndarray, list, tuple)): plt.axvline(vconst[0], color='#859900') plt.text(vconst[0], Y[0], label[6]) plt.axvspan(vconst[0] + vconst[1], vconst[0] - vconst[1], alpha=0.35, color='gray')
def show_chain_evolution(samples): # measurement indicators x_vals = Settings.Simulation.get_xvals() measurer = create_measurer() measurement_lims = zip(measurer.left_limits, measurer.right_limits) for l_idx, r_idx in measurement_lims: plt.axhspan(x_vals[l_idx], x_vals[r_idx], facecolor='r', alpha=0.3) # ground truth lines for a in Settings.Simulation.IC.ground_truth: plt.axhline(a, color='k') # actual chain values for i in range(3): plt.plot(samples[i, :], label=Settings.Simulation.IC.names[i]) # shock locations shock_locs = [ BurgersEquation.riemann_shock_pos(samples[0, i] + 1, samples[1, i], samples[2, i], Settings.Simulation.T_end) for i in range(len(samples[0, :])) ] plt.plot(shock_locs, label="Shock location") # computed characteristics # l_b = len_burn_in(samples) # if l_b == len(samples[0, :]): # tau = "burn-in not finished" # else: # tau = uncorrelated_sample_spacing(samples[:, l_b:]) # plt.text(0, 1.6, f"burn-in: {l_b}\ndecorrelation-length: {tau}") # characteristics plt.text(0, 1.6, ( f"burn-in: {Settings.Sampling.burn_in}\n" f"sampling-interval: {Settings.Sampling.sample_interval}\n" f"usable samples: {(Settings.Sampling.N - Settings.Sampling.burn_in)/Settings.Sampling.sample_interval}" )) plt.ylim(-1, 1.8) plt.title("Chain evolution") plt.legend() store_figure(Settings.filename() + "_chain")
def plot_data(rank_dates, rank_data, filename): min_rank = min(rank_data) max_rank = max(rank_data) a = strict_floor(min_rank) b = strict_ceil(max_rank) #plt.plot([1,2,3,4]) plt.plot(rank_dates, rank_data, marker="o") NEXT_GAP = 0.15 TO_JUMP = 0.6 def adjust(limit, x): return limit if abs(x - limit) < TO_JUMP else x lower_limit = adjust(a, min_rank) - NEXT_GAP upper_limit = adjust(b, max_rank) + NEXT_GAP plt.yticks(*calculate_ticks(a, b)) #plt.tick_params(axis='x', which='minor', bottom=False #plt.axes().yaxis.set_ticks([-1,0,1])#.set_minor_locator(matplotlib.ticker.MultipleLocator(1)) #plt.axes().yaxis.grid(True) for i, tick in enumerate(plt.axes().yaxis.get_major_ticks()): if i % 2 == 1: tick.tick1line.set_markersize(0) tick.tick2line.set_markersize(0) else: tick.gridOn = True #plt.axhspan(i, i+.2, facecolor='0.2', alpha=0.5) for i in range(a - 1, b + 1): if i % 2 == 0: down = max(upper_limit, i) up = min(lower_limit, i + 1) plt.axhspan(i, i + 1, facecolor='gray', alpha=0.25) plt.ylim(lower_limit, upper_limit) X_BORDER = 5 plt.xlim(min(rank_dates) - X_BORDER, max(rank_dates) + X_BORDER) plt.axes().xaxis.set_ticklabels([]) plt.axes().xaxis.set_ticks([]) fig = plt.figure(1) plot = fig.add_subplot(111) plot.tick_params(axis='both', which='major', labelsize=8) #plt.show() plt.savefig(filename) plt.close()
def lgr_cal(co2cal, ch4cal, filename): data = lgr_read(filename) # create savenames for figures co2savename = '{:5.1f}co2'.format(co2cal) co2savename = co2savename.replace('.', '_') + '.png' ch4savename = '{:5.1f}ch4'.format(ch4cal) ch4savename = ch4savename.replace('.', '_') + '.png' # initialize the date and co2/ch4 lists dt = [] co2 = [] ch4 = [] # read in the data from the record for i in range(len(data)): dt.append(data[i][0]) co2.append(data[i][1].get('[CO2]_ppm')) ch4.append(data[i][1].get('[CH4]_ppm')) plt.figure() co2mean = np.nanmean(co2) co2std = np.nanstd(co2) figtitle = 'cal tank = {:5.1f} ppm LGR mean = {:5.1f} ppm; LGR std ={:5.1f} ppm'.format( co2cal, co2mean, co2std) plt.title(figtitle) plt.plot_date(dt, co2, 'b.') plt.axhspan(co2mean + co2std, co2mean - co2std, color='y', alpha=0.5, lw=0) plt.axhline(y=co2cal, color='r') plt.savefig(co2savename, dpi=100) plt.close() plt.figure() ch4mean = np.nanmean(ch4) ch4std = np.nanstd(ch4) figtitle = 'cal tank = {:6.4f} ppm LGR mean = {:6.4f} ppm; LGR std ={:6.4f} ppm'.format( ch4cal / 1000., ch4mean, ch4std) plt.plot_date(dt, ch4, 'b.') plt.title(figtitle) plt.axhspan(ch4mean + ch4std, ch4mean - ch4std, color='y', alpha=0.5, lw=0) plt.axhline(y=ch4cal / 1000., color='r') plt.savefig(ch4savename, dpi=100) plt.close()
def graphing(self): plt.plot(self.df["Close"], color='black') plt.axhspan(self.level1, self.minimum_price, alpha=0.4, color='lightsteelblue') plt.axhspan(self.level2, self.level1, alpha=0.5, color='papayawhip') plt.axhspan(self.level3, self.level2, alpha=0.5, color='lightgreen') plt.axhspan(self.maximum_price, self.level3, alpha=0.5, color='lightskyblue') plt.legend(['Historical Data'], loc='upper left') # Legend plt.ylabel("Price") plt.xlabel("Date") plt.legend(loc=2) plt.show()
def draw_cardio_zones(Z1, Z2, Z3, Z4, Z5, total_minutes): plt.axhspan(Z4[1], Z5[1], facecolor='r', alpha=0.5, zorder=0, label="Z5 Maximum") plt.axhspan(Z3[1], Z4[1], facecolor='y', alpha=0.5, zorder=0, label="Z4 Anaerobic") plt.axhspan(Z2[1], Z3[1], facecolor='g', alpha=0.5, zorder=0, label="Z3 Aerobic") plt.axhspan(Z1[1], Z2[1], facecolor='b', alpha=0.5, zorder=0, label="Z2 Burn fat") plt.axhspan(Z1[0], Z1[1], facecolor='c', alpha=0.5, zorder=0, label="Z1 Recovery") #plt.axhspan(0, Z1[0], facecolor='c', alpha=0.5, zorder=0, label="Z1 Recovery") texto1 = "Z1=%d-%d bpm" % (int(Z1[0]), int(Z1[1])) + " (50-60%) FCM" texto2 = "Z2=%d-%d bpm" % (int(Z2[0]), int(Z2[1])) + " (60-70%) FCM" texto3 = "Z3=%d-%d bpm" % (int(Z3[0]), int(Z3[1])) + " (70-80%) FCM" texto4 = "Z4=%d-%d bpm" % (int(Z4[0]), int(Z4[1])) + " (80-90%) FCM" texto5 = "Z5=%d-%d bpm" % (int(Z5[0]), int(Z5[1])) + " (90-100%) FCM" plt.text(50 - len(texto1), Z1[0] + 5, texto1, size="large", alpha=1) plt.text(50 - len(texto2), Z2[0] + 5, texto2, size="large", alpha=1) plt.text(50 - len(texto3), Z3[0] + 5, texto3, size="large", alpha=1) plt.text(50 - len(texto4), Z4[0] + 5, texto4, size="large", alpha=1) plt.text(50 - len(texto5) + 1, Z5[0] + 5, texto5, size="large", alpha=1)
def main(): dat_directory = "/home/paw/science/betapic/data/calc/" ISM, D = np.genfromtxt(dat_directory + 'ColDens.txt', unpack=True) # Plot the results fig = plt.figure(figsize=(6, 4.5)) #fig = plt.figure(figsize=(14,5)) fontlabel_size = 18 tick_size = 18 params = { 'backend': 'wxAgg', 'lines.markersize': 2, 'axes.labelsize': fontlabel_size, 'font.size': fontlabel_size, 'legend.fontsize': 15, 'xtick.labelsize': tick_size, 'ytick.labelsize': tick_size, 'text.usetex': True } plt.rcParams.update(params) plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) plt.rcParams['text.usetex'] = True plt.rcParams['text.latex.unicode'] = True plt.axhspan(19.3, 19.5, color="#D3D3D3") plt.scatter(ISM, D, color="black", zorder=3) #x = np.arange(16,10,0) #plt.xlabel(r'Wavelength (\AA)') plt.plot([16, 20], [19.4, 19.4], '--', color="#4682b4", lw=2.0) plt.plot([18.4, 18.4], [18.0, 20.0], '--', color="#4682b4", lw=2.0) plt.plot([16, 20], [19.5, 19.5], '--k') plt.plot([16, 20], [19.3, 19.3], '--k') plt.xlim(16.9, 19.45) plt.ylim(18.8, 19.55) #plt.legend(loc='lower left', numpoints=1) plt.minorticks_on() plt.xlabel(r'$\log(N_{\mathrm{H}})_{\mathrm{ISM}}$') plt.ylabel(r'$\log(N_{\mathrm{H}})_{\mathrm{disk}}$') fig.tight_layout() #plt.savefig('../plots/ism_bp.pdf', bbox_inches='tight', pad_inches=0.1,dpi=300) plt.show()
def _plot_summary(summary, savepath, device): assert 'serial' in summary if device in {'cpu', 'cuda'}: assert 'fp32' in summary['serial'] baseline = summary['serial']['fp32']['serial:fp32:avg'].loc[1] else: assert 'bf16' in summary['serial'] baseline = summary['serial']['bf16']['serial:bf16:avg'].loc[1] plt.clf() for mode, throughputs in summary.items(): for prec, df in throughputs.items(): if mode == 'serial': plt.axhline( y=df['serial:{}:avg'.format(prec)].loc[1] / baseline, label='serial:{}'.format(prec), color=_COLORS[mode], linestyle=_LINESTYLES[prec], ) plt.axhspan( df['serial:{}:min'.format(prec)].loc[1] / baseline, df['serial:{}:max'.format(prec)].loc[1] / baseline, facecolor=_COLORS[mode], alpha=0.3, ) else: plt.plot( df.index.values, df['{}:{}:avg'.format(mode, prec)] / baseline, label='{}:{}'.format(mode, prec), color=_COLORS[mode], linestyle=_LINESTYLES[prec], ) plt.fill_between( df.index.values, df['{}:{}:min'.format(mode, prec)] / baseline, df['{}:{}:max'.format(mode, prec)] / baseline, facecolor=_COLORS[mode], alpha=0.3, ) lgd = plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.xlabel("B") plt.ylabel("Normalized Throughput") plt.rcParams['savefig.dpi'] = 300 plt.savefig('{}.png'.format(savepath), bbox_inches='tight')
def plot_matrix_clusters(matrix, bands, new_clusters, cc, ylabel, save_to=None): fig = plt.figure(figsize=(7, 8)) n = len(set(new_clusters)) use_map = matplotlib.cm.get_cmap('hsv') colour_map = colors.ListedColormap( [(1, 1, 1, 0)] + [tuple([(use_map(i * 1.0 / n)[j]) * 0.4 for j in range(3)] + [1]) for i in range(1, n + 1)]) alt_map = colors.ListedColormap( [[(use_map(i * 1.0 / n)[j]) * 0.7 for j in range(3)] + [1] for i in range(1, n + 1)]) draw_matrix = matrix * np.array(new_clusters)[:, np.newaxis] msh = plt.pcolormesh(draw_matrix, cmap=colour_map) plt.subplots_adjust(top=0.904) plt.axis([0, draw_matrix.shape[1], 0, draw_matrix.shape[0]]) msh.axes.invert_yaxis() c_bar = plt.colorbar(msh, shrink=0.5) c_bar.set_cmap(alt_map) c_bar.draw_all() c_bar.set_ticks([i + 0.5 for i in range(n)]) c_bar.ax.set_yticklabels(range(1, n + 1)) c_bar.set_label('Cluster number') al = 0.3 for i in range(n): for item in cc[i]: plt.axhspan(item, item + 1, alpha=al, lw=0, color=use_map((i + 1.0) / n)) plt.gca().set_ylabel(ylabel) plt.gca().set_xlabel('Annotations') for i, x in enumerate(bands): if len(x.split('/')[-1].rstrip('0123456789')) > 20: bands[i] = 'LocatedEntity' # print x.split('/')[-1].rstrip('0123456789') msh.axes.set_xticks([j + 0.5 for j in range(len(bands))], minor=False) msh.axes.set_xticks(range(len(bands)), minor=True) msh.axes.set_xticklabels([item.split('/')[-1].rstrip('0123456789') for item in bands], rotation=90) plt.tick_params(axis='x', which='major', bottom='off', top='off', labelbottom='on') fig.autofmt_xdate(bottom=0.19, ha='right', rotation=60) # plt.show() if save_to is None: plt.show() else: plt.savefig(save_to, dpi=400)
async def _history(ctx, user, limit: str): try: games = int(limit) + 1 if games < 2: raise Exception except: if limit == "all": games = None else: await ctx.send("Limit should be a positive integer or \"all\"") return player = state.get_player(user.id) if player is None: await ctx.send("{} has not played yet.".format(user.mention)) return ys = list(map(lambda x: x[1], player.history)) ys = [Player().conservative_rating()] + ys xs = [i for i in range(len(ys))] if games is not None and len(ys) > games: ys = ys[-games:] xs = xs[-games:] ymin = min(ys) ymax = max(ys) dy = 0.05 * (ymax - ymin) ymin -= dy ymax += dy plt.clf() alpha = 0.3 rating_min = 0 for rank in state.ranks: rating_max = rank["limit"] plt.axhspan(rating_min, rating_max, alpha=alpha, color=rank["color"]) rating_min = rating_max plt.xticks(xs[::round(len(xs) / 15)]) plt.ylim([ymin, ymax]) plt.grid() plt.plot(xs, ys, "black") plt.title(f"{user.display_name}'s rating history") plt.xlabel('game #') plt.ylabel('rating') plt.savefig(fname='plot') await ctx.send(file=discord.File('plot.png')) os.remove('plot.png')
def make_chart(self, prices, current_price, title=None, optional_feature=None, no_show=False, save_to='img.png', **save_kws): """Draw a chart to visualize green zone and current situation.""" with Img(st=title, legend='f' if optional_feature is not None else 'a', no_show=no_show) as img: # Зелёная зона - где продажа без убытка green_min = min_price_for_profit(current_price) plt.axhspan(green_min, prices.max(), alpha=.2, color='g', label=f'Non-loss zone @ {green_min}+') Img.labels('Datetime', f'Price, {self.api.instrument.currency}') plot_time_series(prices, label=f'{self.api.instrument.name} ({self.api.instrument.ticker})') plt.axhline(current_price, color='orange', ls=':', label=f'Current price = {current_price}') if optional_feature is not None: plot_time_series(optional_feature, label=optional_feature.name, color='red', ax=plt.gca().twinx(), alpha=0.5) if save_kws: img.savefig(fname=save_to, **save_kws)
def plot_hr_config_y(hrc, HRmin=100, HRmax=190): """Plot HR_config data where HR is along the y-axis.""" # Set ticks on x-axis num_ticks = 7 y = list(np.linspace(HRmin, HRmax, num_ticks)) yticks = list(np.linspace(HRmin, HRmax, num_ticks)) plt.yticks(y, yticks) # Mark HR zones plt.axhspan(HRmin, hrc.Z1_h, facecolor='c', alpha=0.2) plt.axhspan(hrc.Z2_l, hrc.Z2_h, facecolor='b', alpha=0.2) plt.axhspan(hrc.Z3_l, hrc.Z3_h, facecolor='g', alpha=0.2) plt.axhspan(hrc.Z4_l, hrc.Z4_h, facecolor='y', alpha=0.2) plt.axhspan(hrc.Z5_l, HRmax, facecolor='r', alpha=0.2) colors = [ mpatches.Patch(color='c', label='Z1'), mpatches.Patch(color='b', label='Z2'), mpatches.Patch(color='g', label='Z3'), mpatches.Patch(color='y', label='Z4'), mpatches.Patch(color='r', label='Z5') ] # Mark HR thresholds lt = plt.axhline(y=hrc.lthr, linewidth=1.0, color='k', dashes=(5, 5), label='LT') vt = plt.axhline(y=hrc.vthr, linewidth=1.0, color='k', dashes=(10, 10), label='VT') rcp = plt.axhline(y=hrc.rcphr, linewidth=1.0, color='k', dashes=(2, 2), label="RCP") thresholds = [lt, vt, rcp] # Add legend plt.legend(handles=colors + thresholds, loc='upper left')
def draw(self): date_index = self.calstockasset.get_daily_index_list() # TOOD : date index에서 5일 단위로 값을 넣는다던지.. plt.figure(1, figsize=(8, 4)) plt.title("My Graph") value_list = self.calstockasset.get_daily_revenu_sum_list() # value가 List다. plt.plot(date_index, value_list, c='seagreen', lw=2) # plt.legend(graphStyle.stockNames) plt.xticks(rotation=45) plt.gca().invert_xaxis() plt.grid(True) # # 0 base line plt.axhspan(-0.1, 0.1, color='red') #, alpha=1) plt.show()
def _plot_summary(summary, savedir, field): plt.clf() for mode, metrics in summary.items(): for prec, df in metrics.items(): if mode == 'serial': plt.axhline( y=df['serial:{}:avg'.format(prec)].loc[1], label='serial:{}'.format(prec), color=_COLORS[mode], linestyle=_LINESTYLES[prec], ) plt.axhspan( df['serial:{}:min'.format(prec)].loc[1], df['serial:{}:max'.format(prec)].loc[1], facecolor=_COLORS[mode], alpha=0.3, ) else: plt.plot( df.index.values, df['{}:{}:avg'.format(mode, prec)], label='{}:{}'.format(mode, prec), color=_COLORS[mode], linestyle=_LINESTYLES[prec], ) plt.fill_between( df.index.values, df['{}:{}:min'.format(mode, prec)], df['{}:{}:max'.format(mode, prec)], facecolor=_COLORS[mode], alpha=0.3, ) lgd = plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.xlabel("B") plt.ylabel(_PLOT_LABELS[field]) plt.rcParams['savefig.dpi'] = 300 plt.savefig( os.path.join(savedir, '{}.png'.format(field)), bbox_inches='tight', )
def plotStreamlinesYZsurf(vv, rr, r, density=0.8, arrowSize=1.2, mask=0.6, ms=36, offset=1e-6, title='None'): """ Plots streamlines in YZ plane given the position and velocity; The surface is also plotted vv: one dimensional arrays of velocity rr: one dimensional arrays of positions where velocity is computed """ Np, Nt = int(np.size(r)/3), int(np.size(rr)/3); Ng=int(np.sqrt(Nt)) yy, zz = rr[Nt:2*Nt].reshape(Ng, Ng), rr[2*Nt:3*Nt].reshape(Ng, Ng) vy, vz = vv[Nt:2*Nt].reshape(Ng, Ng), vv[2*Nt:3*Nt].reshape(Ng, Ng) for i in range(Np): plt.plot(r[i+Np], r[i+2*Np], 'o', mfc='snow', mec='darkslategray', ms=ms, mew=4 ) spd = np.hypot(vy, vz) rr = np.hypot(yy-r[1], zz-r[2]) spd[rr<mask]=0; spd+=offset plt.pcolormesh(yy, zz, np.log(spd), cmap=plt.cm.gray_r, shading='interp') st=11; sn=st*st; a0=2; ss=np.zeros((2, st*st)) for i in range(st): for j in range(st): ii = i*st+j ss[0, ii] = a0*(-5 + i) ss[1, ii] = 1*(0 + j) plt.streamplot(yy, zz, vy, vz, color="black", arrowsize =arrowSize, arrowstyle='->', start_points=ss.T, density=density) plt.xlim(np.min(yy), np.max(yy)) ww=0.3 plt.ylim(-ww, np.max(zz)) plt.axhspan(-ww, ww, facecolor='black'); plt.axis('off') if title==str('None'): pass elif title==str('1s'): plt.title('$l\sigma=1s$', fontsize=26); elif title==str('2s'): plt.title('$l\sigma=2s$', fontsize=26); elif title==str('3t'): plt.title('$l\sigma=3t$', fontsize=26); else: plt.title(title, fontsize=26);
def drawline(): t = np.arange(-1, 2, .01) s = np.sin(2 * np.pi * t) plt.plot(t, s) plt.axis([-1, 2, -3, 2]) # 画一条直线 plt.axhline(y=0, c='r') # xmin,xmax是倍数,范围(0,1),0最左,1最右边 plt.axhline(y=-1, c='r', xmin=0, xmax=0.75, linewidth=4) plt.axvline(x=0.5, c='g') plt.axvline(x=0, c='g', ymin=0.2, ymax=0.5, linewidth=4) # 画一段范围 plt.axhspan(0, .75, facecolor='0.5', alpha=0.5) plt.axvspan(-1, 0, facecolor='0.5', alpha=0.5) # plt.hlines(hline, xmin=plt.gca().get_xlim()[0], xmax=plt.gca().get_xlim()[1], linestyles=line_style, colors=color) plt.text(0, 1, "1的text数值") plt.show()
def comparing_temps_from_dataframe_by_day(dataframe_thermo, dataframe_SHT1x, string_day, temp_param_MAX, temp_param_MIN, temp_MAX, temp_MIN, temp_limit_SUP, temp_limit_INF): plt.title('Comparation of the temperatures of day %s' % string_day) today_plot_thermo = dataframe_thermo.TEMP_LOG[string_day] today_plot_SHT1x = dataframe_SHT1x.temp[string_day] plt.ylim(temp_limit_INF, temp_limit_SUP) y = np.arange(temp_limit_INF, temp_limit_SUP, 0.2) plt.grid() plt.yticks(y) today_plot_thermo.plot() today_plot_SHT1x.plot() plt.axhspan(temp_param_MIN, temp_param_MAX, facecolor='g', alpha=0.2) plt.axhspan(temp_MIN, temp_MAX, facecolor='g', alpha=0.2) legend(('thermo', 'SHT1x', 'Recommended zone'), loc='upper right') plt.ylabel('Temperature (%sC)' % degree_sign) plt.xlabel('Hours') plt.savefig('static/data/comparing_temps_%s.png' % string_day, orientation='landscape') plt.close()
def plotAvgThroughput(s, n_points, throughputs): x_axis = np.arange(1, n_points + 1) s = s[:n_points] states_tr = setThroughputForStates(s, throughputs) y_axis = [] for i in range(0, len(states_tr)): index = i + 1 y_axis.append(sum(states_tr[:index]) / index) C_I = bootstrapAlgorithm(states_tr, ci_level=0.95, metric='mean') fig, ax1, = plt.subplots() ax1.scatter(x_axis, y_axis, marker='.', color='b', linewidths=1) plt.axhspan(C_I[0], C_I[-1], color='b', alpha=0.2) plt.xlabel("# of state transitions") plt.ylabel("Throughput (Mbit/s)") plt.show()
def save_graph_simple(path, series, stats, xticks, color_map): series.plot(legend=True, color=color_map['main']) mean, deviation, val_min, val_max = stats['mean'], stats['std'], stats[ 'min'], stats['max'] plt.axhspan(mean - deviation, mean + deviation, color=color_map['std']) plt.axhline(mean, color=color_map['mean'], linestyle='--') plt.axhline(val_min, color=color_map['extreme'], linestyle='--') plt.axhline(val_max, color=color_map['extreme'], linestyle='--') # plt.axhspan(mean - deviation, mean + deviation, color='#ffaaff77' ) # plt.axhline(mean, color='r', linestyle='--') # plt.axhline(val_min, color='b', linestyle='--') # plt.axhline(val_max, color='b', linestyle='--') # yticks plt.yticks((val_min, mean, val_max)) plt.xticks(xticks) print(f"saving file {path}: ticks = {plt.xticks()[0]}") plt.savefig(path, format='svg') plt.clf()
def save(l, n, kernel, normalize, output_dir, save_dat, save_plot): out_fname = 'l=%d_n=%d'%(l,n) if save_dat: np.savetxt(os.path.join(output_dir, out_fname+'.dat'), kernel) if save_plot: plt.axhspan(0, 0, ls='dashed') plt.plot(kernel[:,0], kernel[:,1], 'r-', label='kernel') plt.xlabel("r/R") plt.ylabel("K") plt.legend(loc='upper center') plt.title('Kernels for the $\ell=%d,\;n=%d$ mode'%(l,n)) plt.ylim([-5, 5]) #plt.ylim([min(0, min(kernel[:,-2]), min(kernel[:,-1]))-0.1, # max(1, max(kernel[:,-2]), max(kernel[:,-1]))+0.1]) if normalize: plt.xlim([0, 1.01]) else: plt.xlim([0, max(kernel[:,0])]) plt.tight_layout() plt.savefig(os.path.join(output_dir, out_fname+'.png')) plt.close()
def plot_sentiment_graph(team, col): df_team = df_sentiment.loc[df_sentiment['team'] == team] df_team = df_team.groupby(['created']).agg({ 'sentiment_numeric': 'sum' }).reset_index() col.write(""" ### Sentiment trend of the team - """) plt.plot(df_team['created'], df_team['sentiment_numeric'], color='navy') plt.title('Daily Tweets Sentiment Score', fontsize=22) plt.xlabel('Date', fontsize=20) plt.ylabel('Sentiment Score', fontsize=20) plt.axhline(y=0, color='black', linestyle='--') plt.axhspan(0, plt.ylim()[1], facecolor='lightgreen') plt.axhspan(plt.ylim()[0], 0, facecolor='salmon') #plt.xticks('rotation=20') plt.tight_layout() col.pyplot()