def plotuv_freq(antennaPosition,L,dec,h,Nfreqs,lamb0,df): c=3e8 #print "lamb0="+str(lamb0) tabfreq=c/(lamb0)+np.arange(Nfreqs)*df B = baseline_angles(antennaPosition,lamb0) # print B.shape #number of antennas na = len(antennaPosition) #number pair or baseline nbl = na*(na-1)/2 maxuv=0. for i in range (nbl): uv = track_uv_freq(h, tabfreq,B[i, 0], 0., B[i, 1], L, dec, Nfreqs)/1e3; # if i == 0 : print uv if uv.max() > maxuv : maxuv=uv.max() plt.plot(uv[:,0], uv[:,1], 'b.',ms=1,alpha=0.5) plt.plot(-uv[:,0], -uv[:,1], 'r.',ms=1,alpha=0.5) plt.xlabel('u (klambda)') plt.ylabel('v (klambda)') plt.title('uv coverage') mb = maxuv*1.1 #5*np.sqrt((uv**2).sum(1)).max() uv.shape plt.axes().set_aspect('equal') plt.xlim(-mb,mb) plt.ylim(-mb,mb)
def scatter(x, y, equal=False, xlabel=None, ylabel=None, xinvert=False, yinvert=False): """ Plot a scatter with simple formatting options """ plt.scatter(x, y, 200, color=[0.3, 0.3, 0.3], edgecolors="white", linewidth=1, zorder=2) sns.despine() if xlabel: plt.xlabel(xlabel) if ylabel: plt.ylabel(ylabel) if equal: plt.axes().set_aspect("equal") plt.plot([0, max([x.max(), y.max()])], [0, max([x.max(), y.max()])], color=[0.6, 0.6, 0.6], zorder=1) bmin = min([x.min(), y.min()]) bmax = max([x.max(), y.max()]) rng = abs(bmax - bmin) plt.xlim([bmin - rng * 0.05, bmax + rng * 0.05]) plt.ylim([bmin - rng * 0.05, bmax + rng * 0.05]) else: xrng = abs(x.max() - x.min()) yrng = abs(y.max() - y.min()) plt.xlim([x.min() - xrng * 0.05, x.max() + xrng * 0.05]) plt.ylim([y.min() - yrng * 0.05, y.max() + yrng * 0.05]) if xinvert: plt.gca().invert_xaxis() if yinvert: plt.gca().invert_yaxis()
def display_channel_efficiency(self): size = 0 start_time = self.pcap_file[0].time end_time = self.pcap_file[len(self.pcap_file) - 1].time duration = (end_time - start_time)/1000 for i in range(len(self.pcap_file) - 1): size += len(self.pcap_file[i]) ans = (((size * 8) / duration) / BW_STANDARD_WIFI) * 100 ans = float("%.2f" % ans) labels = ['utilized', 'unutilized'] sizes = [ans, 100.0 - ans] colors = ['g', 'r'] # Make a pie graph plt.clf() plt.figure(num=1, figsize=(8, 6)) plt.axes(aspect=1) plt.suptitle('Channel efficiency', fontsize=14, fontweight='bold') plt.title("Bits/s: " + str(float("%.2f" % ((size*8)/duration))),fontsize = 12) plt.rcParams.update({'font.size': 17}) plt.pie(sizes, labels=labels, autopct='%.2f%%', startangle=60, colors=colors, pctdistance=0.7, labeldistance=1.2) plt.show()
def make_shape(pts, max_output_len=100): """ Args: pts: a tuple of points (x,y) to be interpolated max_output_len: the max number of points in the interpolated curve Returns: the pair of interpolated points (xnew,ynew) Raises: ValueError: pts defined a self-intersecting curve """ assert len(pts[0]) == len(pts[1]) pts = tuple(map(lambda x: np.append(x, x[0]), pts)) fit_pts = interp(pts) if curve_intersects(fit_pts): raise ValueError("Curve is self-intersecting") if PLOT_SHAPE: plt.figure() plt.plot(pts[0],pts[1], 'x') plt.plot(fit_pts[0],fit_pts[1]) plt.axes().set_aspect('equal', 'datalim') plt.show() sparse_pts = tuple(map(lambda ls: ls[::len(fit_pts[0]) // max_output_len + 1], fit_pts)) return sparse_pts
def display_PER(self): number_of_pkts = len(self.pcap_file) retransmission_pkts = 0 for pkt in self.pcap_file: if (pkt[Dot11].FCfield & 0x8) != 0: retransmission_pkts += 1 ans = (retransmission_pkts / number_of_pkts)*100 ans = float("%.2f" % ans) labels = ['Standard packets', 'Retransmitted packets'] sizes = [100.0 - ans,ans] colors = ['g', 'firebrick'] # Make a pie graph plt.clf() plt.figure(num=1, figsize=(8, 6)) plt.axes(aspect=1) plt.suptitle('Retransmitted packet', fontsize=14, fontweight='bold') plt.rcParams.update({'font.size': 13}) plt.pie(sizes, labels=labels, autopct='%.2f%%', startangle=60, colors=colors, pctdistance=0.7, labeldistance=1.2) plt.show()
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 drawVectors(transformed_features, components_, columns, plt, scaled): if not scaled: return plt.axes() # No cheating ;-) num_columns = len(columns) # This funtion will project your *original* feature (columns) # onto your principal component feature-space, so that you can # visualize how "important" each one was in the # multi-dimensional scaling # Scale the principal components by the max value in # the transformed set belonging to that component xvector = components_[0] * max(transformed_features[:,0]) yvector = components_[1] * max(transformed_features[:,1]) ## visualize projections # Sort each column by it's length. These are your *original* # columns, not the principal components. important_features = { columns[i] : math.sqrt(xvector[i]**2 + yvector[i]**2) for i in range(num_columns) } important_features = sorted(zip(important_features.values(), important_features.keys()), reverse=True) print "Features by importance:\n", important_features ax = plt.axes() for i in range(num_columns): # Use an arrow to project each original feature as a # labeled vector on your principal component axes plt.arrow(0, 0, xvector[i], yvector[i], color='b', width=0.0005, head_width=0.02, alpha=0.75) plt.text(xvector[i]*1.2, yvector[i]*1.2, list(columns)[i], color='b', alpha=0.75) return ax
def gen_irregular_axes(axes_prop, spacing=0.05, offset=0.05, axis='vert', share=False): if not axis in ['horiz', 'vert']: raise Exception("'axis' must be either 'horiz' or 'vert'") axes_prop = np.array(axes_prop).ravel() axes_prop = axes_prop[::-1] axes_prop /= sum(axes_prop) axes_prop *= (1-offset*2) axes_starts = np.r_[0, np.cumsum(axes_prop)] if axis=='vert': stuff = [ (s, e-s-spacing) for s, e in izip(axes_starts[:-1], axes_starts[1:])] rectangles = [ [spacing, offset+ystart, 1-spacing*2, height] for ystart, height in stuff] else: stuff = [ (s, e-s-spacing) for s, e in izip(axes_starts[:-1], axes_starts[1:])] rectangles = [ [ystart, spacing, height, 1-spacing] for ystart, height in stuff] axes = [None]*len(rectangles) for k,r in enumerate(rectangles): if share and k > 0 and axis == 'vert': axes[k] = plt.axes(r, sharex=axes[0]) elif share and k > 0 and axis=='horiz': axes[k] = plt.axes(r, sharey=axes[0]) else: axes[k] = plt.axes(r) if k > 0 and share and axis=='vert': #axes[k].set_xticks([]) #axes[k].set_xticklabels([]) for label in axes[k].get_xticklabels(): label.set_visible(False) return axes
def _scatter(actual, prediction, args): plt.figure() plt.plot(actual, prediction, 'b'+args['plot_scatter_marker']) xmin=min(actual) xmax=max(actual) ymin=min(prediction) ymax=max(prediction) diagxmin=min(math.fabs(x) for x in actual) diagymin=min(math.fabs(y) for y in prediction) diagpmin=min(diagxmin,diagymin) pmin=min(xmin,ymin) pmax=max(xmax,ymax) plt.plot([diagpmin,pmax],[diagpmin,pmax],'k-') if args['plot_identifier'] != 'NoName': plt.title(args['plot_identifier']) plt.xlabel('Observed') plt.ylabel('Modeled') if args['plot_performance_log'] == True: plt.yscale('log') plt.xscale('log') if args['plot_scatter_free'] != True: plt.axes().set_aspect('equal') if args['plot_dump'] == True: pfname=os.path.join(args['plot_dir'],args['plot_identifier']+'_eiger_scatter.pdf') plt.savefig(pfname,format="pdf") else: plt.show()
def plot_curves(curve1, curve2, size_x, picture_name): """ function eats .dat files """ size_y=size_x shape = [int(size_x),int(size_y)] data_1 = np.loadtxt(curve1) x_1 = data_1[:,0].reshape(shape,order='C') y_1 = data_1[:,1].reshape(shape,order='C') f_1 = data_1[:,2].reshape(shape,order='C') # plt.plot(x_end,rho_end, label='curve 1') a = plt.contour(x_1, y_1, f_1,30, label='curve 1') print np.max(f_1) data_2 = np.loadtxt(curve2) x_2 = data_2[:,0].reshape(shape,order='C') y_2 = data_2[:,1].reshape(shape,order='C') rho_2 = data_2[:,2].reshape(shape,order='C') b = plt.contourf(x_2,y_2,rho_2,30, label='curve 2') # b = plt.contour(xcoords, ycoords, step) print np.max(rho_2) plt.clabel(a, inline=1, fontsize=10) plt.clabel(b, inline=1, fontsize=10) plt.legend() cbar = plt.colorbar(b) # ymax = max(np.max(rho_end1),np.max(rho_end)) # ymin = min(np.min(rho_end),np.min(rho_end1)) # xmax = max(np.max(x_end1),np.max(x_end)) # xmin = min(np.min(x_end),np.min(x_end1)) #print xmax, xmin, ymax, ymin #plt.axis([0,1/6.,0,1]) plt.axes().set_aspect('equal') plt.savefig(str(picture_name)+'.png', dpi=300)
def POST(self): data = web.data() query_data=json.loads(data) start_time=query_data["start_time"] end_time=query_data["end_time"] parameter=query_data["parameter"] query="SELECT "+parameter+",timestamp FROM jplug_data WHERE timestamp BETWEEN "+str(start_time)+" AND "+str(end_time) retrieved_data=list(db.query(query)) LEN=len(retrieved_data) x=[0]*LEN y=[0]*LEN X=[None]*LEN for i in range(0,LEN): x[i]=retrieved_data[i]["timestamp"] y[i]=retrieved_data[i][parameter] X[i]=datetime.datetime.fromtimestamp(x[i],pytz.timezone(TIMEZONE)) #print retrieved_data["timestamp"] with lock: figure = plt.gcf() # get current figure plt.axes().relim() plt.title(parameter+" vs Time") plt.xlabel("Time") plt.ylabel(units[parameter]) plt.axes().autoscale_view(True,True,True) figure.autofmt_xdate() plt.plot(X,y) filename=randomword(12)+".jpg" plt.savefig("/home/muc/Desktop/Deployment/jplug_view_data/static/images/"+filename, bbox_inches=0,dpi=100) plt.close() web.header('Content-Type', 'application/json') return json.dumps({"filename":filename})
def diff_viewer(expected_fname, result_fname, diff_fname): plt.figure(figsize=(16, 16)) plt.suptitle(os.path.basename(expected_fname)) ax = plt.subplot(221) ax.imshow(mimg.imread(expected_fname)) ax = plt.subplot(222, sharex=ax, sharey=ax) ax.imshow(mimg.imread(result_fname)) ax = plt.subplot(223, sharex=ax, sharey=ax) ax.imshow(mimg.imread(diff_fname)) def accept(event): # removes the expected result, and move the most recent result in print('ACCEPTED NEW FILE: %s' % (os.path.basename(expected_fname), )) os.remove(expected_fname) shutil.copy2(result_fname, expected_fname) os.remove(diff_fname) plt.close() def reject(event): print('REJECTED: %s' % (os.path.basename(expected_fname), )) plt.close() ax_accept = plt.axes([0.7, 0.05, 0.1, 0.075]) ax_reject = plt.axes([0.81, 0.05, 0.1, 0.075]) bnext = mwidget.Button(ax_accept, 'Accept change') bnext.on_clicked(accept) bprev = mwidget.Button(ax_reject, 'Reject') bprev.on_clicked(reject) plt.show()
def test_plot_raw_psd(): """Test plotting of raw psds.""" import matplotlib.pyplot as plt raw = _get_raw() # normal mode raw.plot_psd(tmax=2.0) # specific mode picks = pick_types(raw.info, meg='mag', eeg=False)[:4] raw.plot_psd(picks=picks, area_mode='range') ax = plt.axes() # if ax is supplied: assert_raises(ValueError, raw.plot_psd, ax=ax) raw.plot_psd(picks=picks, ax=ax) plt.close('all') ax = plt.axes() assert_raises(ValueError, raw.plot_psd, ax=ax) ax = [ax, plt.axes()] raw.plot_psd(ax=ax) plt.close('all') # topo psd raw.plot_psd_topo() plt.close('all') # with a flat channel raw[5, :] = 0 assert_raises(ValueError, raw.plot_psd)
def test_extents(): # tests that one can set the extents of a map in a variety of coordinate # systems, for a variety of projection uk = [-12.5, 4, 49, 60] uk_crs = ccrs.Geodetic() ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(uk, crs=uk_crs) # enable to see what is going on (and to make sure it is a plot of the uk) # ax.coastlines() assert_array_almost_equal(ax.viewLim.get_points(), np.array([[-12.5, 49.], [4., 60.]])) ax = plt.axes(projection=ccrs.NorthPolarStereo()) ax.set_extent(uk, crs=uk_crs) # enable to see what is going on (and to make sure it is a plot of the uk) # ax.coastlines() assert_array_almost_equal(ax.viewLim.get_points(), np.array([[-1034046.22566261, -4765889.76601514], [333263.47741164, -3345219.0594531]]) ) # given that we know the PolarStereo coordinates of the UK, try using # those in a PlateCarree plot ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([-1034046, 333263, -4765889, -3345219], crs=ccrs.NorthPolarStereo()) # enable to see what is going on (and to make sure it is a plot of the uk) # ax.coastlines() assert_array_almost_equal(ax.viewLim.get_points(), np.array([[-17.17698577, 48.21879707], [5.68924381, 60.54218893]]) )
def plot_q_qhat(q, t): # Plot Potential Vorticity plt.clf() plt.subplot(2,1,1) plt.pcolormesh(xx/1e3,yy/1e3,q) plt.colorbar() plt.axes([-Lx/2e3, Lx/2e3, -Ly/2e3, Ly/2e3]) name = "PV at t = %5.2f" % (t/(3600.0*24.0)) plt.title(name) # compute power spectrum and shift ffts qe = np.vstack((q0,-np.flipud(q))) qhat = np.absolute(fftn(qe)) kx = fftshift((parms.ikx/parms.ikx[0,1]).real) ky = fftshift((parms.iky/parms.iky[1,0]).real) qhat = fftshift(qhat) Sx, Sy = int(parms.Nx/2), parms.Ny Sk = 1.5 # Plot power spectrum plt.subplot(2,1,2) #plt.pcolor(kx[Sy:Sy+20,Sx:Sx+20],ky[Sy:Sy+20,Sx:Sx+20],qhat[Sy:Sy+20,Sx:Sx+20]) plt.pcolor(kx[Sy:int(Sk*Sy),Sx:int(Sk*Sx)],ky[Sy:int(Sk*Sy),Sx:int(Sk*Sx)], qhat[Sy:int(Sk*Sy),Sx:int(Sk*Sx)]) plt.axis([0, 10, 0, 10]) plt.colorbar() name = "PS at t = %5.2f" % (t/(3600.0*24.0)) plt.title(name) plt.draw()
def fit_circle_nonlin_lstsq(x, y, x0=0, y0=0, r0=1): def residual(params, x, y): xc, yc, r = params return (x-xc)**2 + (y-yc)**2 - r**2 def Jacobian(params, x, y): xc, yc, r = params J = np.zeros((x.shape[0], params.shape[0])) J[:,0] = -2*(x-xc) J[:,1] = -2*(y-yc) J[:,2] = -2*r return J # nonlinear least squares fit params0 = np.array([x0, y0, r0]) params = scipy.optimize.leastsq(residual, params0, args=(x,y), Dfun=Jacobian)[0] # plotting xc, yc, r = params t = np.linspace(0,2*np.pi,num=10000) xx = xc + r*np.cos(t) yy = yc + r*np.sin(t) plt.close('all') plt.xlabel('x'), plt.xlim([np.min(xx),np.max(xx)]) plt.ylabel('y'), plt.ylim([np.min(yy),np.max(yy)]) plt.plot(x, y, 'ok', ms=10) # input data points plt.plot(xx, yy, '-b', lw=2) # nonlinear fit plt.plot(xc, yc, 'or', ms=10) # nonlinear fit center plt.axes().set_aspect('equal')
def advance(self, t, plotresult=False): y0 = self.concs * self.molWeight y0 = append(y0, self.thickness) yt = odeint(self.rightSideofODE, y0, t) if (plotresult): import matplotlib.pyplot as plt plt.figure() plt.axes([0.1, 0.1, 0.6, 0.85]) plt.semilogy(t, yt) plt.ylabel('mass concentrations (kg/m3)') plt.xlabel('time(s)') #plt.legend(self.speciesnames) for i in range(len(self.speciesnames)): plt.annotate( self.speciesnames[i], (t[-1], yt[-1, i]), xytext=(20, -5), textcoords='offset points', arrowprops=dict(arrowstyle="-")) plt.show() self.thickness = yt[-1][-1] ytt = yt[-1][:-1] # for iii in range(len(ytt)): # if ytt[iii]<0: # ytt[iii]=0. molDens = ytt / self.molWeight self.concs = molDens self.molFrac = molDens / sum(molDens) self.massFrac = ytt / sum(ytt)
def svm_sgd_plot(X, Y): w = np.zeros(len(X[0])) eta = 1 epochs = 10000 errors = [] for epoch in range(1, epochs): error = 0 for i,x in enumerate(X): if(Y[i] * np.dot(X[i], w)) < 1: w = w + eta * ( (X[i] * Y[i]) + (-2 * (1/epoch) * w) ) error = 1 else: w = w + eta * (-2 * (1/epoch) * w) errors.append(error) plt.plot(errors, '|') plt.ylim(0.5,1.5) plt.axes().set_yticklabels([]) plt.xlabel('Epoch') plt.ylabel('Misclassified') plt.show() return w
def test_simple(): fig = plt.figure() # un-comment to debug # recursive_pickle(fig) pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL) ax = plt.subplot(121) pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL) ax = plt.axes(projection='polar') plt.plot(list(xrange(10)), label='foobar') plt.legend() # recursive_pickle(fig) pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL) # ax = plt.subplot(121, projection='hammer') # recursive_pickle(ax, 'figure') # pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL) plt.figure() plt.bar(left=list(xrange(10)), height=list(xrange(10))) pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL) fig = plt.figure() ax = plt.axes() plt.plot(list(xrange(10))) ax.set_yscale('log') pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
def main(): plt.rcParams['font.sans-serif']=['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.title("显示正弦波") plt.xlabel("x 轴") plt.ylabel("y 轴") X = np.linspace(-np.pi, np.pi, 256, endpoint=True) Y = np.sin(2*X) plt.axes([0.025, 0.025, 0.95, 0.95]) plt.plot (X, Y+1, color='blue', alpha=1.00) plt.fill_between(X, 1, Y+1, color='blue', alpha=.25) plt.plot (X, Y-1, color='blue', alpha=1.00) plt.fill_between(X, -1, Y-1, (Y-1) > -1, color='blue', alpha=.25) plt.fill_between(X, -1, Y-1, (Y-1) < -1, color='red', alpha=.25) plt.xlim(-np.pi, np.pi) plt.xticks([]) plt.ylim(-3.5, 3.5) plt.yticks([]) #plt.savefig('../figures/plot_ex.png',dpi=48) plt.show()
def plot_bicycle(): plt.clf() plt.axes() ax = plt.gca() #ax.add_patch(plt.Rectangle((10,0), 10, 20, fill=False, ec='k')) #car ax.add_patch(plt.Rectangle((21,1), .75, 2, fill=False, ec='k')) #wheel ax.add_patch(plt.Rectangle((21.33,10), .75, 2, fill=False, ec='k', angle=20)) #wheel ax.add_patch(plt.Rectangle((21.,4.), .75, 2, fill=True, ec='k', angle=5, ls='dashdot', alpha=0.3)) #wheel plt.arrow(0, 2, 20.5, 0, fc='k', ec='k', head_width=0.5, head_length=0.5) plt.arrow(0, 2, 20.4, 3, fc='k', ec='k', head_width=0.5, head_length=0.5) plt.arrow(21.375, 2., 0, 8.5, fc='k', ec='k', head_width=0.5, head_length=0.5) plt.arrow(23, 2, 0, 2.5, fc='k', ec='k', head_width=0.5, head_length=0.5) #ax.add_patch(plt.Rectangle((10,0), 10, 20, fill=False, ec='k')) plt.text(11, 1.0, "R", fontsize=18) plt.text(8, 2.2, r"$\beta$", fontsize=18) plt.text(20.4, 13.5, r"$\alpha$", fontsize=18) plt.text(21.6, 7, "w (wheelbase)", fontsize=18) plt.text(0, 1, "C", fontsize=18) plt.text(24, 3, "d", fontsize=18) plt.plot([21.375, 21.25], [11, 14], color='k', lw=1) plt.plot([21.375, 20.2], [11, 14], color='k', lw=1) plt.axis('scaled') plt.xlim(0,25) plt.axis('off') plt.show()
def plot(X, z, fname='plot.pdf'): """Plot data according to labels in z. Use PCA to project in 2D in case data is higher dimensional. """ z_unique = np.unique(z) if len(X[0]) > 2: pca = PCA(n_components=2) X_new = pca.fit_transform(X) else: X_new = X fig = plt.figure() ax = fig.add_subplot(111) #colors = iter(['#1b9e77', '#d95f02', '#7570b3']) colors = iter(['#e41a1c', '#377eb8', '#4daf4a']) for k in z_unique: idx = np.where(z==k) x = X_new[idx][:,0] y = X_new[idx][:,1] ax.plot(x, y, 'bo', markersize=4, alpha=.5, color=next(colors)) ax.set_xticks([]) ax.set_yticks([]) plt.axes().set_aspect('equal', 'datalim') fig.tight_layout() fig.savefig(fname)
def plot_skew(y_cv, preds, N = 50, Nmax = 20, start=0, detailed=True): ''' plot the roc curves with different skews to see what the distribution of the data is ... ''' powers = np.linspace(start, N, Nmax)[1:] aucs = [] if detailed: plot_distribution(y_cv, preds**N) for xx, i in enumerate(powers): fpr, tpr, thresholds = metrics.roc_curve(y_cv, preds**i) roc_auc = metrics.auc(fpr, tpr) if detailed: plot_roc(fpr, tpr, roc_auc, newPlot=(xx==0), label='%.1f'%i, color=(i/N,0.5,1-i/N)) aucs.append( roc_auc ) if detailed: plt.legend() plt.figure(figsize=(4, 3)) plt.axes([0.17, 0.18, 0.94-0.17, 0.96-0.18]) plt.plot(powers, aucs, 's') intPowers = np.linspace(start, N, 100)[1:] # plt.plot(intPowers, np.poly1d(np.polyfit(powers, aucs, 2))( intPowers ), color='black' ) plt.xlabel('power') plt.ylabel('AUC') return powers, aucs
def add_clusters(self, cl_class, num_clusters, cl_color): mypatches=[] for i,(x,y) in enumerate(self.coords): if cl_class[i] == Cluster.NO_CLUSTER: continue if self.lattice == Lattice.Hex: patch = RegularPolygon((x,-y), numVertices=6, radius=3, facecolor=cl_color[cl_class[i] - 1], edgecolor='none') else: patch = Rectangle((x, -y), 5.2, 5.2, facecolor=cl_color[cl_class[i] - 1], edgecolor='none') mypatches.append(patch) p = PatchCollection(mypatches, match_original=True) self.ax.add_collection(p) self.ax.autoscale_view() plt.axes().set_aspect('equal', 'datalim') # Double the size of the canvas current_figure = plt.gcf() w, h = current_figure.get_size_inches() current_figure.set_size_inches(w*2, h*2) # Shrink current axis by 20% to make space for the legend box = self.ax.get_position() self.ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) handles = [] for i in range(num_clusters): handles.append(plt.Line2D((0,1),(0,0), color=cl_color[i])) plt.legend(handles, [ "cluster " + str(x) for x in range(1, num_clusters + 1)], loc='center left', bbox_to_anchor=(1, 0.5))
def display(workspace, **params): def update(val): vmax = smax.val vmin = smin.val im.set_clim(vmax=vmax, vmin=vmin) fig.canvas.draw_idle() fig = pylab.figure() '''displays a gather using imshow''' vmax = np.amax(workspace) vmin = np.amin(workspace) im = pylab.imshow(workspace.T, aspect='auto', cmap='Greys', vmax =vmax, vmin=vmin) pylab.colorbar() axcolor = 'lightgoldenrodyellow' axmax = pylab.axes([0.08, 0.06, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units smax = Slider(axmax, 'vmax', vmin, vmax, valinit=vmax) smax.on_changed(update) axmin = pylab.axes([0.08, 0.03, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units smin = Slider(axmin, 'vmin', vmin, vmax, valinit=vmin) smin.on_changed(update) smin.on_changed(update) pylab.show()
def make_ax3(): paper_single(TW=8, AR=0.9) f = plt.figure() from matplotlib.ticker import NullFormatter, MaxNLocator nullfmt = NullFormatter() # no labels # definitions for the axes left, width = 0.1, 0.65 bottom, height = 0.1, 0.6 bottom_h = bottom+height+0.02 left_h = left+width+0.02 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] ax = plt.axes(rect_scatter) plt.minorticks_on() axx = plt.axes(rect_histx) plt.minorticks_on() axy = plt.axes(rect_histy) plt.minorticks_on() # no labels axx.xaxis.set_major_formatter(nullfmt) axy.yaxis.set_major_formatter(nullfmt) axy.xaxis.set_major_locator(MaxNLocator(3)) axx.yaxis.set_major_locator(MaxNLocator(3)) return f,ax,axx,axy
def generateToy(): print 'loading values' if not os.path.isfile('values2.p'): z_data = np.loadtxt('values2.dat') pkl.dump( z_data, open( 'values2.p', "wb" ),pkl.HIGHEST_PROTOCOL ) else: z_data = pkl.load(open('values2.p',"rb")) print 'loaded' #x = np.random.normal(size=1000) z_data_subset = z_data[0:20000] plot_range = [50,400] print 'max',max(z_data_subset),'min',min(z_data_subset) plt.yscale('log', nonposy='clip') plt.axes().set_ylim(0.0000001,0.17) hist(z_data_subset,range=plot_range,bins=100,normed=1,histtype='stepfilled', color=['lightgrey'], label=['100 bins']) #hist(z_data_subset,range=plot_range,bins='knuth',normed=1,histtype='step',linewidth=1.5, # color=['navy'], label=['knuth']) hist(z_data_subset,range=plot_range,bins='blocks',normed=1,histtype='step',linewidth=2.0, color=['crimson'], label=['b blocks']) plt.legend() #plt.yscale('log', nonposy='clip') #plt.axes().set_ylim(0.0000001,0.17) plt.xlabel(r'$m_{\ell\ell}$ (GeV)') plt.ylabel('A.U.') plt.title(r'Z$\to\mu\mu$ Data') plt.savefig('z_data_hist_comp.png') plt.show()
def display(ncube, ngrid, path): # Time delay before displaying new plot. delay = 0.001 # Determines the number of files over which to loop. # NOTE: These files must be the only files in the directory for this approach to work. files = os.listdir(path) numFiles = len(files) # Prepares the plot to be displayed. pl.ion() pl.figure(1) # Loops over all files and extracts the component-based data. for i in xrange(1, numFiles + 1): x, y, z, vx, vy, vz = np.genfromtxt(path + "TimeStamp" + str(i) + ".txt", dtype = float, unpack = True) # Plots x positions against y positions to get an xy-plane slice. pl.scatter(x, y, s = 3) pl.axes().set_xlim((0., float(ngrid * ncube))) pl.axes().set_ylim((0., float(ngrid * ncube))) pl.xlabel("X Position") pl.ylabel("Y Position") pl.title("N-Body Simulation: 2D Slice") # Draws the plot and then delays the next iteration. pl.draw() time.sleep(delay) pl.clf() # Closes the plot at the very end. pl.close(1)
def generate(self): # path = os.path.join(self.output_root, self.make_filename) plt.figure() plt.axes(**self.plot_settings['axis']) plt.imshow(self.frames(self.data), **self.plot_settings['image']) plt.savefig(self.path, bbox_inches="tight", pad_inches=0, format='png') plt.close()
def __save(self, n, plot, sfile): p.figure(figsize=sfile) p.xlabel(plot.xlabel) p.ylabel(plot.ylabel) p.xscale(plot.xscale) p.yscale(plot.yscale) p.grid() for curvetype, args, kwargs in plot.curves: if curvetype == "plot": p.plot(*args, **kwargs) elif curvetype == "imshow": p.imshow(*args, **kwargs) elif curvetype == "hist": p.hist(*args, **kwargs) elif curvetype == "bar": p.bar(*args, **kwargs) p.axes().set_aspect(plot.aspect) if plot.legend: p.legend(shadow=0, loc=plot.loc) if not os.path.isdir(plot.dir): os.mkdir(plot.dir) if plot.pgf: p.savefig(plot.dir + plot.name + ".pgf") print(plot.name + ".pgf") if plot.pdf: p.savefig(plot.dir + plot.name + ".pdf", bbox_inches="tight") print(plot.name + ".pdf") p.close()
a0 = board.get_pin('a:0:i') # Tkinter canvas top = Tkinter.Tk() top.title("Tkinter + matplotlib") # Create flag to work with indefinite while loop flag = Tkinter.BooleanVar(top) flag.set(True) pyplot.ion() pData = [0.0] * 25 fig = pyplot.figure() pyplot.title('Potentiometer') ax1 = pyplot.axes() l1, = pyplot.plot(pData) pyplot.ylim([0, 1]) # Create Start button and associate with onStartButtonPress method startButton = Tkinter.Button(top, text="Start", command=onStartButtonPress) startButton.grid(column=1, row=2) # Create Stop button and associate with onStopButtonPress method pauseButton = Tkinter.Button(top, text="Pause", command=onPauseButtonPress) pauseButton.grid(column=2, row=2) # Create Exit button and destroy the window exitButton = Tkinter.Button(top, text="Exit", command=onExitButtonPress) exitButton.grid(column=3, row=2)
def recreate_image(codebook, labels, w, h): """Recreate the (compressed) image from the code book & labels""" d = codebook.shape[1] image = np.zeros((w, h, d)) label_idx = 0 for i in range(w): for j in range(h): image[i][j] = codebook[labels[label_idx]] label_idx += 1 return image # Display all results, alongside original image plt.figure(1) plt.clf() ax = plt.axes([0, 0, 1, 1]) plt.axis('off') plt.title('Original image (96,615 colors)') plt.imshow(china) plt.figure(2) plt.clf() ax = plt.axes([0, 0, 1, 1]) plt.axis('off') plt.title('Quantized image (64 colors, K-Means)') plt.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h)) plt.figure(3) plt.clf() ax = plt.axes([0, 0, 1, 1]) plt.axis('off')
def main(): for p_level in plot_levels: # Set pressure height contour min/max if p_level == 925: clev_min = 660. clev_max = 810. elif p_level == 850: clev_min = 1435. clev_max = 1530. elif p_level == 700: clev_min = 3090. clev_max = 3155. elif p_level == 500: clev_min = 5800. clev_max = 5890. else: print 'Contour min/max not set for this pressure level' # Set potential temperature min/max if p_level == 925: clevpt_min = 300. clevpt_max = 312. elif p_level == 850: clevpt_min = 302. clevpt_max = 310. elif p_level == 700: clevpt_min = 312. clevpt_max = 320. elif p_level == 500: clevpt_min = 325. clevpt_max = 332. else: print 'Potential temperature min/max not set for this pressure level' # Set specific humidity min/max if p_level == 925: clevsh_min = 0.012 clevsh_max = 0.020 elif p_level == 850: clevsh_min = 0.007 clevsh_max = 0.017 elif p_level == 700: clevsh_min = 0.002 clevsh_max = 0.010 elif p_level == 500: clevsh_min = 0.001 clevsh_max = 0.005 else: print 'Specific humidity min/max not set for this pressure level' #clevs_col = np.arange(clev_min, clev_max) clevs_lin = np.arange(clev_min, clev_max, 5) p_level_constraint = iris.Constraint(pressure=p_level) for plot_diag in plot_diags: for experiment_id in experiment_ids: expmin1 = experiment_id[:-1] pp_file = '%s_%s_on_p_levs_mean_by_hour.pp' % (experiment_id, plot_diag) pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, pp_file) pcube = iris.load_cube(pfile, p_level_constraint) # For each hour in cube height_pp_file = '%s_408_on_p_levs_mean_by_hour.pp' % ( experiment_id) height_pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, height_pp_file) height_cube = iris.load_cube(height_pfile, p_level_constraint) print pcube print height_cube #time_coords = cube_f.coord('time') add_hour_of_day(pcube, pcube.coord('time')) add_hour_of_day(height_cube, height_cube.coord('time')) #pcube.remove_coord('time') #cube_diff.remove_coord('time') #height_cube.remove_coord('time') #height_cube_diff.remove_coord('time') #p_cube_difference = iris.analysis.maths.subtract(pcube, cube_diff, dim='hour') #height_cube_difference = iris.analysis.maths.subtract(height_cube, height_cube_diff, dim='hour') #pdb.set_trace() #del height_cube, pcube, height_cube_diff, cube_diff for t, time_cube in enumerate( pcube.slices(['grid_latitude', 'grid_longitude'])): #pdb.set_trace() print time_cube height_cube_slice = height_cube.extract( iris.Constraint(hour=time_cube.coord('hour').points)) # Get time of averagesfor plot title h = u.num2date( np.array(time_cube.coord('hour').points, dtype=float)[0]).strftime('%H%M') #Convert to India time from_zone = tz.gettz('UTC') to_zone = tz.gettz('Asia/Kolkata') h_utc = u.num2date( np.array(time_cube.coord('hour').points, dtype=float)[0]).replace(tzinfo=from_zone) h_local = h_utc.astimezone(to_zone).strftime('%H%M') fig = plt.figure(**figprops) cmap = plt.cm.RdBu_r ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low, lon_high, lat_low + degs_crop_bottom, lat_high - degs_crop_top)) m =\ Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high, rsphere = 6371229) #pdb.set_trace() lat = time_cube.coord('grid_latitude').points lon = time_cube.coord('grid_longitude').points cs = time_cube.coord_system('CoordSystem') lons, lats = np.meshgrid(lon, lat) lons, lats = iris.analysis.cartography.unrotate_pole\ (lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) x, y = m(lons, lats) if plot_diag == 'temp': min_contour = clevpt_min max_contour = clevpt_max cb_label = 'K' main_title = '8km Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), potential temperature (colours),\ and wind (vectors) %s UTC %s IST' % ( h, h_local) tick_interval = 2 clev_number = max_contour - min_contour + 1 elif plot_diag == 'sp_hum': min_contour = clevsh_min max_contour = clevsh_max cb_label = 'kg/kg' main_title = '8km Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), specific humidity (colours),\ and wind (vectors) %s UTC %s IST' % ( h, h_local) tick_interval = 0.002 clev_number = (max_contour - min_contour + 0.001) * (10**3) clevs = np.linspace(min_contour, max_contour, clev_number) #clevs = np.linspace(-3, 3, 32) cont = plt.contourf(x, y, time_cube.data, clevs, cmap=cmap, extend='both') #cont = iplt.contourf(time_cube, clevs, cmap=cmap, extend='both') cs_lin = iplt.contour(height_cube_slice, clevs_lin, colors='#262626', linewidths=1.) plt.clabel(cs_lin, fontsize=14, fmt='%d', color='black') #del time_cube #plt.clabel(cont, fmt='%d') #ax.stock_img() ax.coastlines(resolution='110m', color='#262626') gl = ax.gridlines(draw_labels=True, linewidth=0.5, color='#262626', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False #gl.xlines = False dx, dy = 10, 10 gl.xlocator = mticker.FixedLocator( range(int(lon_low_tick), int(lon_high_tick) + dx, dx)) gl.ylocator = mticker.FixedLocator( range(int(lat_low_tick), int(lat_high_tick) + dy, dy)) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 12, 'color': '#262626'} #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'} gl.ylabel_style = {'size': 12, 'color': '#262626'} cbar = fig.colorbar(cont, orientation='horizontal', pad=0.05, extend='both') cbar.set_label('%s' % cb_label, fontsize=10, color='#262626') #cbar.set_label(time_cube.units, fontsize=10, color='#262626') cbar.set_ticks( np.arange(min_contour, max_contour + tick_interval, tick_interval)) ticks = (np.arange(min_contour, max_contour + tick_interval, tick_interval)) cbar.set_ticklabels(['${%.1f}$' % i for i in ticks]) cbar.ax.tick_params(labelsize=10, color='#262626') #main_title='Mean Rainfall for EMBRACE Period -%s UTC (%s IST)' % (h, h_local) #main_title=time_cube.standard_name.title().replace('_',' ') #model_info = re.sub(r'[(\']', ' ', model_info) #model_info = re.sub(r'[\',)]', ' ', model_info) #print model_info file_save_name = '%s_%s_%s_hPa_and_geop_height_%s' % ( experiment_id, plot_diag, p_level, h) save_dir = '%s%s/%s' % (save_path, experiment_id, plot_diag) if not os.path.exists('%s' % save_dir): os.makedirs('%s' % (save_dir)) #plt.show() fig.savefig('%s/%s_notitle.png' % (save_dir, file_save_name), format='png', bbox_inches='tight') plt.title('%s UTC %s IST' % (h, h_local)) fig.savefig('%s/%s_short_title.png' % (save_dir, file_save_name), format='png', bbox_inches='tight') model_info = re.sub( '(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL) plt.title('\n'.join( wrap('%s\n%s' % (main_title, model_info), 1000, replace_whitespace=False)), fontsize=16) fig.savefig('%s/%s.png' % (save_dir, file_save_name), format='png', bbox_inches='tight') fig.clf() plt.close() #del time_cube gc.collect()
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import TextBox fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.2) t = np.arange(-2.0, 2.0, 0.001) s = t**2 initial_text = "t ** 2" l, = plt.plot(t, s, lw=2) def submit(text): ydata = eval(text) l.set_ydata(ydata) ax.set_ylim(np.min(ydata), np.max(ydata)) plt.draw() axbox = plt.axes([0.1, 0.05, 0.8, 0.075]) text_box = TextBox(axbox, 'Evaluate', initial=initial_text) text_box.on_submit(submit) plt.show()
calgo = l_alg[ja] print(' *** '+calgo+' => '+cf_nemo[ja]) id_nemo = Dataset(cf_nemo[ja]) F_nemo[:,ja] = id_nemo.variables[cv_nemo][:,1,1] ; # it's 3x3 spatial domain, taking middle point ! id_nemo.close() if l_more: #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # How does all this look on on a figure? cfig = l_var_rf[jv]+'_'+calgo+'.'+fig_ext print(' *** will plot '+cfig) fig = plt.figure(num=1, figsize=size_fig, facecolor='w', edgecolor='k') ax1 = plt.axes([0.08, 0.25, 0.9, 0.7]) # plt.plot(vtime, F_nemo[:,ja], label='NEMO['+calgo+']', zorder=1) plt.plot(vtime, F_rf_m[:], color='k', label='MEAN REF!', zorder=10) # +- rtol enveloppe: plt.fill_between(vtime, F_rf_m[:]-F_rf_t[:], F_rf_m[:]+F_rf_t[:], alpha=0.2) # ax1.grid(color='k', linestyle='-', linewidth=0.3) plt.legend(loc='best', ncol=1, shadow=True, fancybox=True) plt.savefig(cfig, dpi=int(rDPI), transparent=False) plt.close(1) print('') #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Does the field look okay with respect to reference +- tolerance ?
def __init__(self, images, shape): fig = plt.figure(figsize=(10, 6)) # subplot positions h_nav = [Size.Fixed(0.5), Size.Fixed(2.5)] v_nav = [Size.Fixed(0.5), Size.Scaled(1.0), Size.Fixed(0.5)] h_im = [Size.Fixed(0.5), Size.Scaled(1.0), Size.Fixed(0.5)] v_im = [Size.Fixed(0.5), Size.Scaled(1.0), Size.Fixed(0.5)] nav = Divider(fig, (0.0, 0.0, 0.2, 1.), h_nav, v_nav, aspect=False) image = Divider(fig, (0.2, 0.0, 0.8, 1.), h_im, v_im, aspect=True) image.set_anchor('C') # Toolbar menu box ax1 = LocatableAxes(fig, nav.get_position()) ax1.set_axes_locator(nav.new_locator(nx=1, ny=1)) ax1.get_xaxis().set_visible(False) ax1.get_yaxis().set_visible(False) fig.add_axes(ax1, label='toolbar') ax1.text(0.05, 0.45, "Filter", weight='heavy', transform=ax1.transAxes) # Image space ax2 = LocatableAxes(fig, image.get_position()) ax2.set_axes_locator(image.new_locator(nx=1, ny=1)) fig.add_axes(ax2, label='image_space') self.callback = ImageIndex(images, shape, fig) # Navigation ## Go to ax_text_index = plt.axes([0.59, 0.05, 0.1, 0.075]) ip = InsetPosition(ax1, [0.2, 0.84, 0.3, 0.05]) ax_text_index.set_axes_locator(ip) entry_index = TextBox(ax_text_index, 'Go to', initial="0") entry_index.on_submit(self.callback.submit_index) ## Previous ax_prev = plt.axes([0.7, 0.05, 0.075, 0.075]) ip = InsetPosition(ax1, [0.55, 0.84, 0.15, 0.05]) ax_prev.set_axes_locator(ip) bprev = Button(ax_prev, '<<') bprev.on_clicked(self.callback.prev) ## Next ax_next = plt.axes([0.81, 0.05, 0.075, 0.075]) ip = InsetPosition(ax1, [0.75, 0.84, 0.15, 0.05]) ax_next.set_axes_locator(ip) bnext = Button(ax_next, '>>') bnext.on_clicked(self.callback.next) # Bounding Boxes ax_chec = plt.axes([0.1, 0.05, 0.35, 0.075]) ip = InsetPosition(ax1, [0.05, 0.5, 0.9, 0.3]) ax_chec.set_axes_locator(ip) ax_chec.text(0.05, 0.85, "Bounding Boxes", transform=ax_chec.transAxes) check = CheckButtons(ax_chec, ('characters', 'lines'), (False, False)) check.on_clicked(self.callback.update_bboxes) # Filtering ## Image ax_text_image = plt.axes([0.1, 0.1, 0.1, 0.075]) ip = InsetPosition(ax1, [0.26, 0.38, 0.64, 0.05]) ax_text_image.set_axes_locator(ip) entry_image = TextBox(ax_text_image, 'images', initial="image_id,image_id") entry_image.on_submit(self.callback.submit_images) ## Characters ax_text_char = plt.axes([0.1, 0.2, 0.1, 0.075]) ip = InsetPosition(ax1, [0.21, 0.3, 0.69, 0.05]) ax_text_char.set_axes_locator(ip) entry_char = TextBox(ax_text_char, 'chars', initial="U+3055,U+3056") entry_char.on_submit(self.callback.submit_chars) ## Reset ax_reset = plt.axes([0., 0., 1., 1.]) ip = InsetPosition(ax1, [0.05, 0.2, 0.2, 0.05]) ax_reset.set_axes_locator(ip) breset = Button(ax_reset, 'Reset') breset.on_clicked(self.callback.reset) plt.show()
np.matmul(np.linalg.pinv(sigma), np.atleast_2d(np.array([x - mu[0, 0], y - mu[0, 1]])).T) ))[0]) + 10000 * (1 / (2 * np.pi * np.linalg.det(sigma))) * np.exp( -.5 * (np.matmul( np.array([x - mu[1, 0], y - mu[1, 1]]), np.matmul(np.linalg.pinv(sigma), np.array([x - mu[1, 0], y - mu[1, 1]]))))) x = np.linspace(0, 100, 100) y = np.linspace(0, 100, 100) z = f(x[:, None], y[None, :]) z = np.rot90(np.fliplr(z)) # fig = plt.figure() # ax = plt.axes(projection='3d') # ax.contour3D(x, y, z, 100) # ax.set_xlabel('x') # ax.set_ylabel('y') # ax.set_zlabel('z') # ax.set_title('3D Contour') # plt.show() fig = plt.figure() ax = plt.axes() ax.contour(x, y, z) ax.set_xlabel('x') ax.set_ylabel('y') plt.show()
def populate_figure(self): # updates GUI button placement, colors, etc self.display.clear() button_color = [0.792156862745098, 0.8823529411764706, 1.0] if self.saving == 1: self.saving_text = self.fig.text(0.875, 0.879, 'Saving', fontsize=10, fontweight='bold', color=[0.933, 0.463, 0]) else: try: self.saving_text.remove() except (ValueError, AttributeError): pass self.notes_text = self.fig.text(0.852, 0.575, 'Notes', fontsize=10, color="black") axmodnotes = plt.axes([0.852, 0.45, 0.125, 0.12]) initial_modnotes = str(self.obj.clone.modification_notes) if initial_modnotes == "nan": initial_modnotes = "" self.notestextbox = TextBox(axmodnotes, '', initial=initial_modnotes) self.notestextbox.on_submit(self.set_notes) axmodifier = plt.axes([0.875, 0.37, 0.1, 0.035]) self.modifiertextbox = TextBox(axmodifier, 'Initials', initial=str( self.params['default_modifier'])) self.modifiertextbox.on_submit(self.change_default_modifier) axflip = plt.axes([0.50, 0.01, 0.1, 0.075]) self.flipbutton = Button(axflip, 'Flip', color=button_color, hovercolor=button_color) self.flipbutton.on_clicked(self.obj.flip_button_press) axedges = plt.axes([0.60, 0.01, 0.1, 0.075]) self.edgebutton = Button(axedges, 'Toggle Edges', color=button_color, hovercolor=button_color) self.edgebutton.on_clicked(self.obj.edge_button_press) axtogdorsal = plt.axes([0.70, 0.01, 0.1, 0.075]) self.togdorsalbutton = Button(axtogdorsal, 'Toggle Dorsal Fit', color=button_color, hovercolor=button_color) self.togdorsalbutton.on_clicked(self.obj.toggle_dorsal_button_press) axdel = plt.axes([0.025, 0.01, 0.1, 0.075]) self.delcheckbutton = Button(axdel, 'Delete Checkpoint', color=button_color, hovercolor=button_color) self.delcheckbutton.on_clicked(self.obj.delete_selected_checkpoint) axsave = plt.axes([0.875, 0.8, 0.1, 0.075]) self.savebutton = Button(axsave, 'Save', color=button_color, hovercolor=button_color) self.savebutton.on_clicked(self.save) axblur = plt.axes([0.25, 0.01, 0.1, 0.035]) self.blurtextbox = TextBox(axblur, 'Gaussian Blur StDev', initial=str(self.obj.edge_blur)) self.blurtextbox.on_submit(self.set_edge_blur) axreset = plt.axes([0.40, 0.01, 0.1, 0.075]) self.resetbutton = Button(axreset, 'Reset', color=button_color, hovercolor=button_color) self.resetbutton.on_clicked(self.reset_button_press) if self.curr_idx + 1 < len(self.clone_list): axnext = plt.axes([0.875, 0.01, 0.1, 0.075]) self.nextbutton = Button(axnext, 'Next', color=button_color, hovercolor=button_color) self.nextbutton.on_clicked(self.next_button_press) if self.curr_idx > 0: axprev = plt.axes([0.875, 0.085, 0.1, 0.075]) self.prevbutton = Button(axprev, 'Previous', color=button_color, hovercolor=button_color) self.prevbutton.on_clicked(self.prev_button_press) self.obj.draw()
'ResultsDirectory': Results_Path } ResultImage, TransformParameterMap = ElastixRegistration(Dictionary) ResultImage_Array = sitk.GetArrayFromImage(ResultImage) ## Plot registration results Figure, Axes = plt.subplots(1, 1, figsize=(8.25, 6.75), dpi=100) Mid_Position = int(round(uCT_Scan_Array.shape[2] / 2)) uCT_Show = Axes.imshow(uCT_Scan_Array[:, :, Mid_Position], cmap='bone', alpha=1) HRpQCT_Show = Axes.imshow(ResultImage_Array[:, :, Mid_Position], cmap='jet', alpha=0.5) SliderAxis = plt.axes([0.25, 0.15, 0.65, 0.03]) Mid_Position_Slider = Slider(SliderAxis, 'Y Position', 0, uCT_Scan_Array.shape[1], valinit=Mid_Position) def Update(Value): Position = Mid_Position_Slider.Value uCT_Show.set_data(uCT_Scan_Array[:, :, int(Position)]) HRpQCT_Show.set_data(ResultImage_Array[:, :, int(Position)]) Figure.canvas.draw_idle() Mid_Position_Slider.on_changed(Update) Axes.set_title(Sample + ' Registration Results')
def main(): parser = build_parser() options = parser.parse_args() if not os.path.isfile(options.network): parser.error("Network %s does not exist. (Did you forget to download it?)" % options.network) if not os.path.isfile(options.model_save_dir + 'checkpoint'): parser.error("Pretrained model %s does not exist.)" % options.network) if not options.from_webcam or options.from_screenshot: parser.error("You must choose either getting the image from webcam or from screen shot." % options.network) style_images = [imread(style) for style in options.styles] # Start with the first one with 1.0 weight and 0.0 for all other ones. current_style_blend_weights = [1.0 if i == 0 else 0.0 for i,_ in enumerate(style_images)] one_hot_vector_container = n_style_feedforward_net.one_hot_vector_container(np.array([current_style_blend_weights])) plt.ion() fig, ax = plt.subplots() plt.subplots_adjust(left=0.25, bottom=0.25) ax.set_title("Real Time Neural Style") im = ax.imshow(np.zeros((options.height, options.width, 3)) + 128,vmin=0,vmax=255) # Blank starting image axcolor = 'lightgoldenrodyellow' slider_axes = [plt.axes([0.25, 0.21 - i * 0.02, 0.65, 0.02], axisbg=axcolor) for i, style in enumerate( options.styles)] sliders = [Slider(slider_axes[i], style, 0.0, 1.0, valinit=current_style_blend_weights[i]) for i, style in enumerate(options.styles)] fig.show() im.axes.figure.canvas.draw() plt.pause(0.001) tstart = None def update(val): for i, slider in enumerate(sliders): current_style_blend_weights[i] = slider.val one_hot_vector_container.vec = np.array([current_style_blend_weights]) for slider in sliders: slider.on_changed(update) for iteration, image in n_style_feedforward_net.style_synthesis_net(path_to_network=options.network, height=options.height, width=options.width, styles=style_images, iterations=None, batch_size=1, one_hot_vector_for_restore_and_generate=one_hot_vector_container, style_only=options.texture_synthesis_only, use_johnson=options.use_johnson, use_skip_noise_4=options.use_skip_noise_4, save_dir=options.model_save_dir, do_restore_and_generate=True, from_screenshot=options.from_screenshot, from_webcam=options.from_webcam): # We must do this clip step before we display the image. Otherwise the color will be off. image = np.clip(image, 0, 255).astype(np.uint8) if tstart is None: tstart = time.time() # Change the data in place instead of create a new window. ax.set_title(str(iteration)) im.set_data(image) im.axes.figure.canvas.draw() plt.pause(0.001) print ('FPS:', iteration / (time.time() - tstart + 0.001)) plt.ioff() plt.show()
def test_check_bunch_of_radio_buttons(): rax = plt.axes([0.05, 0.1, 0.15, 0.7]) widgets.RadioButtons(rax, ('B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'B10', 'B11', 'B12', 'B13', 'B14', 'B15'))
def draw(self): # updates all visualizations depending on current state of the GUI, # and redraws the GUI image and buttons self.display.clear() buttoncolor = [0.792156862745098, 0.8823529411764706, 1.0] axaddcheck = plt.axes([0.025, 0.085, 0.1, 0.075]) self.addcheckbutton = Button(axaddcheck, 'Add Checkpoint', color=buttoncolor, hovercolor=buttoncolor) self.addcheckbutton.on_clicked(self.add_checkpoint_button_press) if self.add_checkpoint: self.addcheckbutton.color = "green" self.addcheckbutton.hovercolor = "green" self.display.imshow(self.image, cmap="gray") axaccept = plt.axes([0.875, 0.7, 0.1, 0.075]) self.acceptbutton = Button(axaccept, 'Accept Changes', color=buttoncolor, hovercolor=buttoncolor) self.acceptbutton.on_clicked(self.accept) if self.clone.accepted: self.acceptbutton.color = "blue" self.acceptbutton.hovercolor = "blue" axmodified = plt.axes([0.875, 0.6, 0.1, 0.075]) self.modifiedbutton = Button(axmodified, 'Mark as Modified', color=buttoncolor, hovercolor=buttoncolor) self.modifiedbutton.on_clicked(self.modified_clicked) if self.clone.modified: self.modifiedbutton.color = "blue" self.modifiedbutton.hovercolor = "blue" axmask = plt.axes([0.025, 0.185, 0.05, 0.075]) self.maskbutton = Button(axmask, 'Mask', color=buttoncolor, hovercolor=buttoncolor) self.maskbutton.on_clicked(self.mask) axunmask = plt.axes([0.075, 0.185, 0.05, 0.075]) self.unmaskbutton = Button(axunmask, 'Unmask', color=buttoncolor, hovercolor=buttoncolor) self.unmaskbutton.on_clicked(self.unmask) if self.mask_clicked: self.maskbutton.color = "green" self.maskbutton.hovercolor = "green" if self.unmask_clicked: self.unmaskbutton.color = "green" self.unmaskbutton.hovercolor = "green" if self.show_dorsal_edge: try: self.display.scatter(self.de[:, 1], self.de[:, 0], c="blue") except TypeError: pass if self.edges: checkpoint_color = "yellow" else: checkpoint_color = "black" try: self.display.scatter(self.checkpoints[:, 1], self.checkpoints[:, 0], c=checkpoint_color) except TypeError: pass self.display.scatter(self.clone.tail_tip[1], self.clone.tail_tip[0], c='red') self.display.text(self.clone.tail_tip[1], self.clone.tail_tip[0], 'tail_tip', color='red') self.display.scatter(self.clone.tail[1], self.clone.tail[0], c='red') self.display.text(self.clone.tail[1], self.clone.tail[0], 'tail', color='red') self.display.axis('off') self.display.set_title(self.clone.filepath, color="black") self.display.figure.canvas.draw()
def jview(var, tindex, jindex, gridid, filename=None, \ cmin=None, cmax=None, clev=None, clbformat='%.2f', \ fill=False, contour=False, d=4, irange=None, \ hrange=None, fts=None, title=None, map=False, \ pal=None, clb=True, outfile=None): """ jview(var, tindex, jindex, gridid, {optional switch}) optional switch: - filename if defined, load the variable from file - cmin set color minimum limit - cmax set color maximum limit - clev set the number of color step - fill use contourf instead of pcolor - contour overlay contour (request fill=True) - d contour density (default d=4) - irange i range - hrange h range - fts set font size (default: 12) - title add title to the plot - map if True, draw a map showing islice location - pal set color map (default: cm.jet) - clb add colorbar (defaul: True) - outfile if defined, write figure to file plot a constante-j slice of variable var. If filename is provided, var must be a string and the variable will be load from the file. grid can be a grid object or a gridid. In the later case, the grid object correponding to the provided gridid will be loaded. """ # get grid if type(gridid).__name__ == 'ROMS_Grid': grd = gridid else: grd = pyroms.grid.get_ROMS_grid(gridid) # get variable if filename == None: var = var else: data = pyroms.io.Dataset(filename) var = data.variables[var] Np, Mp, Lp = grd.vgrid.z_r[0,:].shape if tindex is not -1: assert len(var.shape) == 4, 'var must be 4D (time plus space).' K, N, M, L = var.shape else: assert len(var.shape) == 3, 'var must be 3D (no time dependency).' N, M, L = var.shape # determine where on the C-grid these variable lies if N == Np and M == Mp and L == Lp: Cpos='rho' lon = grd.hgrid.lon_vert lat = grd.hgrid.lat_vert mask = grd.hgrid.mask_rho if N == Np and M == Mp and L == Lp-1: Cpos='u' lon = 0.5 * (grd.hgrid.lon_vert[:,:-1] + grd.hgrid.lon_vert[:,1:]) lat = 0.5 * (grd.hgrid.lat_vert[:,:-1] + grd.hgrid.lat_vert[:,1:]) mask = grd.hgrid.mask_u if N == Np and M == Mp-1 and L == Lp: Cpos='v' lon = 0.5 * (grd.hgrid.lon_vert[:-1,:] + grd.hgrid.lon_vert[1:,:]) lat = 0.5 * (grd.hgrid.lat_vert[:-1,:] + grd.hgrid.lat_vert[1:,:]) mask = grd.hgrid.mask_v if N == Np+1 and M == Mp and L == Lp: Cpos='w' lon = grd.hgrid.lon_vert lat = grd.hgrid.lat_vert mask = grd.hgrid.mask_rho # get constante-j slice if tindex == -1: var = var[:,:,:] else: var = var[tindex,:,:,:] if fill == True: jslice, zj, lonj, latj, = pyroms.tools.jslice(var, jindex, grd, \ Cpos) else: jslice, zj, lonj, latj, = pyroms.tools.jslice(var, jindex, grd, \ Cpos, vert=True) # plot if cmin is None: cmin = jslice.min() else: cmin = float(cmin) if cmax is None: cmax = jslice.max() else: cmax = float(cmax) if clev is None: clev = 100. else: clev = float(clev) dc = (cmax - cmin)/clev ; vc = np.arange(cmin,cmax+dc,dc) if pal is None: pal = cm.jet else: pal = pal if fts is None: fts = 12 else: fts = fts #pal.set_over('w', 1.0) #pal.set_under('w', 1.0) #pal.set_bad('w', 1.0) pal_norm = colors.BoundaryNorm(vc,ncolors=256, clip = False) # clear figure #plt.clf() if map is True: # set axes for the main plot in order to keep space for the map if fts < 12: ax=None else: ax = plt.axes([0.15, 0.08, 0.8, 0.65]) else: if fts < 12: ax=None else: ax=plt.axes([0.15, 0.1, 0.8, 0.8]) if fill is True: cf = plt.contourf(lonj, zj, jslice, vc, cmap = pal, norm = pal_norm, axes=ax) else: cf = plt.pcolor(lonj, zj, jslice, cmap = pal, norm = pal_norm, axes=ax) if clb is True: clb = plt.colorbar(cf, fraction=0.075,format=clbformat) for t in clb.ax.get_yticklabels(): t.set_fontsize(fts) if contour is True: if fill is not True: raise Warning, 'Please run again with fill=True for overlay contour.' else: plt.contour(lonj, zj, jslice, vc[::d], colors='k', linewidths=0.5, linestyles='solid', axes=ax) if irange is not None: plt.xlim(irange) if hrange is not None: plt.ylim(hrange) if title is not None: if map is True: # move the title on the right xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() xt = xmin - (xmax-xmin)/9. yt = ymax + (ymax-ymin)/7. plt.text(xt, yt, title, fontsize=fts+4) else: plt.title(title, fontsize=fts+4) plt.xlabel('Latitude', fontsize=fts) plt.ylabel('Depth', fontsize=fts) if map is True: # draw a map with constant-i slice location ax_map = plt.axes([0.4, 0.76, 0.2, 0.23]) varm = np.ma.masked_where(mask[:,:] == 0, var[var.shape[0]-1,:,:]) xmin, xmax = ax.get_xlim() dd = (lon[jindex,:] - xmin) * (lon[jindex,:] - xmin) start = np.where(dd == dd.min()) dd = (lon[jindex,:] - xmax) * (lon[jindex,:] - xmax) end = np.where(dd == dd.min()) lon_min = lon.min() lon_max = lon.max() lon_0 = (lon_min + lon_max) / 2. lat_min = lat.min() lat_max = lat.max() lat_0 = (lat_min + lat_max) / 2. map = Basemap(projection='merc', llcrnrlon=lon_min, llcrnrlat=lat_min, \ urcrnrlon=lon_max, urcrnrlat=lat_max, lat_0=lat_0, lon_0=lon_0, \ resolution='i', area_thresh=10.) x, y = map(lon,lat) # fill land and draw coastlines map.drawcoastlines() map.fillcontinents(color='grey') #map.drawmapboundary() Basemap.pcolor(map, x, y, varm, axes=ax_map) Basemap.plot(map, x[jindex,start[0]:end[0]], y[jindex,start[0]:end[0]], \ 'k-', linewidth=3, axes=ax_map) if outfile is not None: if outfile.find('.png') != -1 or outfile.find('.svg') != -1 or outfile.find('.eps') != -1: print 'Write figure to file', outfile plt.savefig(outfile, dpi=200, facecolor='w', edgecolor='w', orientation='portrait') else: print 'Unrecognized file extension. Please use .png, .svg or .eps file extension.' return
def plot_diff(slice1, title, lim1, lim2, step): #plt.figure() plt.figure(figsize=(12, 6)) # this works #plt.figure(figsize=(12, 4.8))# this works data = slice1.data lon = slice1.coord('longitude').points lat = slice1.coord('latitude').points new_lon = [] for k in range(len(lon)): if lon[k] > 180: #temp=lon[k] temp = lon[k] - 360 new_lon = np.append(new_lon, temp) else: new_lon = np.append(new_lon, lon[k]) #lon=lon-180 #basemap correction #new_lon=temp #..............basemap requires lat and lon to be in increasing order data_1 = data[:, 0:96] data_2 = data[:, 96:] data_21 = np.hstack((data_2, data_1)) new_lon_1 = new_lon[0:96] new_lon_2 = new_lon[96:] new_lon_21 = np.hstack((new_lon_2, new_lon_1)) data_final = data_21 new_lon_final = new_lon_21 ticks = np.arange(lim1, lim2, step) ticks6 = [1e0, 1e3, 1e5, 1e8, 1e10] ticks6_label = ['1e0', '1e3', '1e5', '1e8', '1e10'] ticks6 = [1e-2, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9] ticks6_label = [ '-1e2', '1e0', '1e1', '1e2', '1e3', '1e4', '1e5', '1e6', '1e7', '1e8', '1e9' ] ticks6 = [1e-33, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9] ticks6_label = [ '-1e2', '1e0', '1e1', '1e2', '1e3', '1e4', '1e5', '1e6', '1e7', '1e8', '1e9' ] ticks6 = [1e-35, 1e-30, 1e-25, 1e-20, 1e-15] ticks6_label = ['1e-35', '1e-30', '1e-25', '1e-20', '1e-15'] ticks6 = [1e-35, 1e-32, 1e-29, 1e-26, 1e-23, 1e-20, 1e-17, 1e-14] ticks6_label = [ '1e-35', '1e-32', '1e-29', '1e-26', '1e-23', '1e-20', '1e-17', '1e-14' ] ticks6 = [1e-20, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0] ticks6 = [1e-20, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0] ticks6 = [-300, -250, -200, -150, -100, -50, 0, 50] # this is a percentage change plot ticks6 = [-100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0] # this is a percentage change plot ticks6_label = [str(o) + '%' for o in ticks6] #ticks6_label = ['1e-35','1e-32','1e-29','1e-26','1e-23','1e-20','1e-17','1e-14'] #ticks6_label = ['1e-35','1e-30','1e-25','1e-20','1e-15'] #ticks6_label = ['-1e2','1e0','1e1','1e2','1e3','1e4','1e5','1e6','1e7','1e8','1e9'] # ticks6 = [-1e-22,1e-30,1e-16] ax = plt.axes(projection=ccrs.PlateCarree()) #data_final = np.where(data_final>1.0,data_final,1e-1) #x=plt.contourf(new_lon_final,lat,data_final,transform=ccrs.PlateCarree(),cmap='RdYlBu_r',levels=ticks) #x=plt.contourf(new_lon_final,lat,data_final,norm=colors.LogNorm(vmin=1e-8,vmax=1e0),transform=ccrs.PlateCarree(),cmap='RdYlBu_r',levels=ticks6) #x=plt.contourf(new_lon_final,lat,data_final,vmin=-100,vmax=0,transform=ccrs.PlateCarree(),cmap='RdYlBu_r',levels=ticks6) x = plt.contourf(new_lon_final, lat, data_final, vmin=-100, vmax=0, transform=ccrs.PlateCarree(), cmap=ruths_colors('davos'), levels=ticks6) #x=plt.contourf(new_lon_final,lat,data_final,norm=colors.LogNorm(vmin=pow(10,-35),vmax=1e-15),transform=ccrs.PlateCarree(),cmap='RdYlBu_r',levels=ticks6) norm = mpl.colors.Normalize(vmin=lim1, vmax=lim2) #plt.title(title,fontdict={'fontsize':16}) plt.title(title, fontsize=18) ax.coastlines() gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='black', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False #gl.xlines = False gl.xlocator = mticker.FixedLocator([-180, -90, 0, 90, 180]) gl.ylocator = mticker.FixedLocator([-90, -45, 0, 45, 90]) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 15, 'color': 'gray'} gl.xlabel_style = {'color': 'black', 'weight': 'bold'} gl.ylabel_style = {'size': 15, 'color': 'gray'} gl.ylabel_style = {'color': 'black', 'weight': 'bold'} """ cbar=plt.colorbar(x,ax=ax,ticks=ticks) cbar.ax.tick_params(labelsize=16) ax.set_aspect('auto') plt.savefig(title+'.png') """ cbar = plt.colorbar(x, ax=ax) cbar.set_ticks(ticks6) cbar.set_ticklabels(ticks6_label) cbar.ax.tick_params(labelsize=16) ax.set_aspect('auto')
nTotal = sum(nResponses) df = nComponents * (nGroups - 1) #(1) Generate Gaussian 1D fields, compute test stat, store field maximum: X2 = [] generator = rft1d.random.GeneratorMulti1D(nTotal, nNodes, nComponents, FWHM, W0) for i in range(nIterations): y = generator.generate_sample() chi2 = here_manova1(y, GROUP) X2.append(chi2.max()) X2 = np.asarray(X2) #(2) Compute survival function (SF) for the field maximumimum: heights = np.linspace(10, 18, 21) sf = np.array([(X2 > h).mean() for h in heights]) sfE = rft1d.chi2.sf(heights, df, nNodes, FWHM) #theoretical sf0D = rft1d.chi2.sf0d(heights, df) #theoretical (0D) #(3) Plot results: pyplot.close('all') ax = pyplot.axes() ax.plot(heights, sf, 'o', label='Simulated') ax.plot(heights, sfE, '-', label='Theoretical') ax.plot(heights, sf0D, 'r-', label='Theoretical (0D)') ax.set_xlabel('$u$', size=20) ax.set_ylabel('$P (\chi^2_\mathrm{max} > u)$', size=20) ax.legend() ax.set_title("MANOVA validation (1D)", size=20) pyplot.show()
import matplotlib.pyplot as plt from random_walk import RandomWalk while True: rw = RandomWalk(50000) rw.fill_walk() plt.figure(dpi=128, figsize=(10, 6)) point_num = list(range(rw.num_points)) plt.scatter(rw.x_label, rw.y_label, c=point_num, cmap=plt.cm.Blues, edgecolors='none', s=15) plt.scatter(0, 0, c='green', edgecolors='none', s=100) plt.scatter(rw.x_label[-1], rw.y_label[-1], c='red', edgecolors='none', s=100) plt.axes().get_xaxis().set_visible(False) plt.axes().get_yaxis().set_visible(False) plt.title("Random Walk", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square Value", fontsize=14) # plt.savefig("random_walk.png", bbox_inches="tight") plt.show() keep_running = input("Make another walk? (y/n): ") if keep_running == 'n': break
def plot_rating(ratings: list, daily_games: list, username, export_video=False, show_graph=True, game_mode="Blitz", big=False, upload=False): if big: fig = plt.figure(figsize=(16, 10)) ax = plt.axes(autoscale_on=True, position=[0.06, 0.06, 0.88, 0.94]) ax2 = plt.twinx(ax) ax2.set_position([0.06, 0.06, 0.88, 0.94]) ax3 = plt.twinx(ax) ax.tick_params(labelsize=15) ax2.tick_params(labelsize=15) ax3.tick_params(labelsize=15) size = 'big' else: fig = plt.figure() ax = plt.axes() ax2 = plt.twinx(ax) ax3 = plt.twinx(ax) size = 'small' line_color = "#3F5D7D" ax.spines["top"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.set_ylabel(f"{username}'s Lichess {game_mode} Rating", color=line_color, fontsize=15) ax.tick_params(labelcolor=line_color, left=False, bottom=False) ax.set_xlabel("Number of games", fontsize=15) ax3.spines["top"].set_visible(False) ax3.spines["bottom"].set_visible(False) ax3.spines["right"].set_visible(False) ax3.spines["left"].set_visible(False) ax3.tick_params(labelright=False, left=False, bottom=False) bar_color = 'grey' ax2.spines["top"].set_visible(False) ax2.spines["bottom"].set_visible(False) ax2.spines["right"].set_visible(False) ax2.spines["left"].set_visible(False) ax2.set_ylabel('Games per day', color=bar_color, fontsize=15) ax2.tick_params(labelcolor=bar_color, right=False, bottom=False) number_of_games = len(ratings) for y in range(800, 3000, 50): ax.plot(range(0, number_of_games), [y] * len(range(0, number_of_games)), "--", lw=0.5, color="black", alpha=0.3) ax.set(ylim=(round_to(min(ratings), 50), round_to(max(ratings), 50, False))) ax3.set(ylim=(round_to(min(ratings), 50), round_to(max(ratings), 50, False))) ax2.set(ylim=(0, round_to(max(daily_games), 5, False))) def animate(i): if i >= len(ratings) - 2: return if i > 0: ax.set(xlim=(0, i + 1)) ax3.set(xlim=(0, i + 1)) ax2.bar(i, daily_games[i], color="black", alpha=0.1, width=1.0) ax.plot([i - 1, i], ratings[i - 1:i + 1], color=line_color) if i > 100: ax3.plot([i - 1, i], [ sum(ratings[i - 100 - 1:i - 1]) / 100, sum(ratings[i - 100:i]) / 100 ], color='orange') anim = animation.FuncAnimation(fig, animate, interval=17, frames=number_of_games - 1) writer = animation.writers['ffmpeg'] writer(fps=60, metadata=dict(artist='kewko')) if export_video: print("Exporting video...") export_file_path = f'export/ChessGraph_{username}_{game_mode}_{size}.mp4' try: os.mkdir('export') print("Export Directory Created ") except FileExistsError: pass anim.save(export_file_path) print(f'Saved {export_file_path}.') if upload: from secrets import streamable_password, streamable_username files = {'file': open(export_file_path, 'rb')} print("Uploading to streamable...") response = requests.post('https://api.streamable.com/upload', auth=HTTPBasicAuth( streamable_username, streamable_password), files=files) graph_url = f"https://streamable.com/{response.json()['shortcode']}" print(graph_url) return graph_url if show_graph: plt.draw() plt.show()
def plot_trajectory(self): ax = plt.axes(projection='3d') ax.plot3D(self.x_, self.y_, self.z_) plt.show()
def main(): # image_path = os.path.join('data', 'uEye_Image_002767.png') # zoom = ((714, 1920), (920, 1830)) image_path = os.path.join('data', 'uEye_Image_000827.png') zoom = ([100, 1312], [400, 1900]) calib = 0.00124 / 400 # mm / px # Arbitrary first guess for gamma initial_surface_tension = 0.04 # N/m surface_tension_range = (0.02, 0.1) # N/m fluid_density = 1000 image1 = load_image(image_path, region=zoom) edges, RZ_edges = detect_edges(image1, method='contour') # Guess parameters center_Z, center_R, radius = fit_circle_tip(edges.shape, RZ_edges, method='ransac', debug=False) theta = guess_angle(edges, center_Z, center_R) # Note that below the method method='SLSQP' can be used also. # Step 1: consider only the surface tension # as it is not guessed so far ini_variables = np.array((initial_surface_tension)) res = minimize(deviation_edge_model_simple, ini_variables, args=(theta, center_R, center_Z, radius, RZ_edges, fluid_density, calib), method='L-BFGS-B', bounds=(surface_tension_range, ), options={ 'maxiter': 10, 'ftol': 1e-2, 'disp': True }) guessed_surface_tension = res.x[0] print(f'Step 1-RMS: {res.fun}') # Step 2: consider all the parameters ini_variables2 = np.array(( guessed_surface_tension, theta, center_R, center_Z, radius, )) param_bounds = ( (guessed_surface_tension - 2e-3, guessed_surface_tension + 2e-3), (theta * 0.7, theta * 1.3), (center_R - 5, center_R + 5), (center_Z - 5, center_Z + 5), (radius - 10, radius + 10), ) res = minimize(deviation_edge_model_full, ini_variables2, args=(RZ_edges, fluid_density, calib), method='L-BFGS-B', bounds=param_bounds, options={ 'maxiter': 100, 'ftol': 1e-6, 'disp': True }) optimal_variables = res.x print(f'Step 2-ini params BFGS: {ini_variables2}') print(f'Step 2-opt params BFGS: {optimal_variables}') print(f'Step 2-RMS: {res.fun}') # Plot RZ_model = young_laplace(*optimal_variables, fluid_density, calib, RZ_edges=RZ_edges, num_points=1e4) oRMS = orthogonal_RMS(RZ_model, RZ_edges) rRMS = radial_RMS(RZ_model, RZ_edges) print(f'OrthoRMS: {oRMS}, RadialRMS {rRMS}') plt.figure() ax = plt.axes() plt.imshow(image1, cmap='gray') circle = plt.Circle((center_R, center_Z), radius=radius, color='c', fill=False) ax.add_patch(circle) plt.plot(*RZ_edges, '*g', markersize=1) plt.plot(*RZ_model, 'r-', markersize=2) plt.plot(center_R, center_Z, 'bo') plt.title(f'Gamma = {optimal_variables[0]:.4} N/m') plt.show()
def main(docopts): docopts["--batch_size"] = int(docopts["--batch_size"]) docopts["--gpu"] = int(docopts["--gpu"]) docopts["--lambda_l2_reg"] = float(docopts["--lambda_l2_reg"]) docopts["--learning_rate"] = float(docopts["--learning_rate"]) docopts["--max_epochs"] = int(docopts["--max_epochs"]) # Logging logging.basicConfig(level=logging.INFO) # # Following http://nbviewer.jupyter.org/github/dmlc/mxnet/blob/master/example/notebooks/simple_bind.ipynb # X, Y = data.get_mnist() iter = mx.io.NDArrayIter(data=X, label=Y, batch_size=docopts["--batch_size"], shuffle=True) if docopts["train"] or docopts["continue"]: m = vae.VAE(ARCHITECTURE) sym = m.training_model() dbatch = iter.next() exe = sym.simple_bind(ctx=mx.gpu(docopts["--gpu"]), data = dbatch.data[0].shape) args = exe.arg_dict grads = exe.grad_dict outputs = dict(zip(sym.list_outputs(), exe.outputs)) if docopts["continue"]: loaded_args = mx.nd.load(os.path.join(docopts["--log"], "parameters")) for name in args: if name != "data": args[name][:] = loaded_args[name] # Initialize parameters xavier = mx.init.Xavier() for name, nd_array in args.items(): if name != "data": xavier(name, nd_array) optimizer = mx.optimizer.create(name="adam", learning_rate=docopts["--learning_rate"], wd=docopts["--lambda_l2_reg"]) updater = mx.optimizer.get_updater(optimizer) # Train keys = sym.list_arguments() optimizer = mx.optimizer.Adam() if docopts["--visualize"]: # Random image last_image_time = time.time() plt.ion() figure = plt.figure() imshow = plt.imshow(np.random.uniform(size=(28,28)), cmap="gray") for epoch in range(docopts["--max_epochs"]): iter.reset() epoch_start_time = time.time() batch = 0 for dbatch in iter: args["data"][:] = dbatch.data[0] exe.forward(is_train=True) exe.backward() if docopts["--visualize"]: # Throttle refresh ratio if time.time() - last_image_time > 0.1: last_image_time = time.time() imshow.set_data(exe.outputs[2][ random.randint(0, docopts["--batch_size"])].reshape( (28,28)).asnumpy()) figure.canvas.draw() figure.canvas.flush_events() for index, key in enumerate(keys): updater(index=index, grad=grads[key], weight=args[key]) kl_divergence = exe.outputs[3].asnumpy() cross_entropy = exe.outputs[4].asnumpy() logging.info("Batch %d: %f mean kl_divergence", batch, kl_divergence.mean()) logging.info("Batch %d: %f mean cross_entropy", batch, cross_entropy.mean()) batch += 1 logging.info("Finish training epoch %d in %f seconds", epoch, time.time() - epoch_start_time) # Save model parameters (including data, to simplify loading / binding) mx.nd.save(os.path.join(docopts["--log"], "parameters"), {x[0]: x[1] for x in args.items() if x[0] != "data"}) elif docopts["test"]: from matplotlib.widgets import Button m = vae.VAE(ARCHITECTURE) sym = m.testing_model() exe = sym.simple_bind(ctx=mx.gpu(docopts["--gpu"]), data=(docopts["--batch_size"], ARCHITECTURE[-1])) args = exe.arg_dict grads = exe.grad_dict outputs = dict(zip(sym.list_outputs(), exe.outputs)) loaded_args = mx.nd.load(os.path.join(docopts["--log"], "parameters")) for name in args: if name != "data": args[name][:] = loaded_args[name] args["data"][:] = np.random.randn(docopts["--batch_size"], ARCHITECTURE[-1]) exe.forward(is_train=True) # testing_model has only 1 output batch = exe.outputs[0].asnumpy().reshape(-1, 28, 28) np.save(os.path.join(docopts["--log"], "output"), batch) imshow = plt.imshow(batch[0], cmap="gray") callback = Index(imshow, batch) axnext = plt.axes([0.8, 0.7, 0.1, 0.075]) axprev = plt.axes([0.8, 0.6, 0.1, 0.075]) next_button = Button(axnext, 'Next') next_button.on_clicked(callback.next) prev_button = Button(axprev, 'Previous') prev_button.on_clicked(callback.prev) plt.show() plt.waitforbuttonpress()
def scat_hist(xdata, ydata, color, x_axis, y_axis, system, analysis, num_b=100, average=False, t0=0, **kwargs): """ Creates 1D scatter plot w/ a 1D histogram Usage: scat_hist(xdata, ydata, color, x_axis, y_axis, system, analysis, num_b) Arguments: xdata, ydata: self-explanatory color: color to be used to plot data x_axis, y_axis: strings to be printed on the axi labels system: descriptor for the system analyzed analysis: descriptor for the analysis performed and plotted num_b: number of bins to be used when binning the data; Default is 100 average: [False|True]; Default is False; if set to True, the function will calc the average, standard dev, and standard dev of mean of the y-data # THERE IS A BUG; if average = True, need to read in xunits for this function to work... t0: index to begin averaging from; Default is 0 kwargs: xunits, yunits: string with correct math text describing the units for the x/y data x_lim, y_lim: list w/ two elements, setting the limits of the x/y ranges of plot plt_title: string to be added as the plot title """ # INITIATING THE PLOT SIZES left, width = 0.1, 0.65 bottom, height = 0.1, 0.8 bottom_h = left_h = left + width + 0.01 rect_scatter = [left, bottom, width, height] rect_histy = [left_h, bottom, 0.2, height] # INITIATING THE PLOT... plt.figure(1, figsize=(10, 8)) axScatter = plt.axes(rect_scatter) axScatter.plot(xdata, ydata, '%s.' % (color)) # READING IN KWARG DICTIONARY INTO SPECIFIC VARIABLES for name, value in kwargs.items(): if name == 'xunits': x_units = value x_axis = '%s (%s)' % (x_axis, value) elif name == 'yunits': y_units = value y_axis = '%s (%s)' % (y_axis, value) elif name == 'x_lim': plt.xlim(value) elif name == 'y_lim': plt.ylim(value) elif name == 'plt_title': plt.title(r'%s' % (value), size='14') plt.grid(b=True, which='major', axis='both', color='#808080', linestyle='--') plt.ylabel(r'%s' % (y_axis), size=20) plt.xlabel(r'%s' % (x_axis), size=20) axScatter.tick_params(axis='both', which='major', labelsize=14) if average != False: avg = np.sum(ydata[t0:]) / len(ydata[t0:]) SD = stdev(ydata[t0:]) SDOM = SD / sqrt(len(ydata[t0:])) plt.axhline(avg, xmin=0.0, xmax=1.0, c='r') axHisty = plt.axes(rect_histy) axHisty.yaxis.set_major_formatter(nullfmt) axHisty.xaxis.set_major_formatter(nullfmt) plt.grid(b=True, which='major', axis='both', color='#808080', linestyle='--') axHisty.hist(ydata, bins=num_b, orientation='horizontal', facecolor='grey', edgecolor='black') axHisty.set_ylim(axScatter.get_ylim()) # CALCULATING THE AVERAGE/SD/SDOM OF THE Y-DATA if average != False: plt.axhline(avg, xmin=0.0, xmax=1.0, c='r') plt.figtext(0.775, 0.810, '%s\n%6.4f $\\pm$ %6.4f %s \nSD = %4.3f %s' % (analysis, avg, SDOM, y_units, SD, y_units), bbox=dict(boxstyle='square', ec='r', fc='w'), fontsize=12) plt.savefig('%s.%s.scat_hist.png' % (system, analysis), dpi=300) plt.close()
#plt.plot(m2_k11_evo_opt*0.975,r2_k11_evo_opt*0.981,c='r',linewidth=1) # m2=0.195 ''' plt.plot(m2_k11_evo_opt, r2_k11_evo_opt, c='r', linewidth=1, alpha=0.8) #,linestyle='dashed',alpha=0.5) plt.plot(m2_k11_evo_std, r2_k11_evo_std, c='k', linewidth=1, alpha=0.8) #,linestyle='dashed') plt.xlabel(r'$M_{2}\ (\rm{M}_{\odot})$', fontsize=16) plt.ylabel(r'$R_{2}\ (\rm{R}_{\odot})$', fontsize=16) plt.tick_params(axis='both', which='major', labelsize=13, width=1.0) plt.tick_params(top='on', right='on') # Period gap #plt.axhspan(0.2254,0.2926,xmin=0.59,xmax=0.70,color='k',alpha=0.05) #plt.axvline(1.363,linestyle='dashed',color='k',linewidth=1,alpha=0.5) #plt.axvspan(1.348,1.378,color='k',alpha=0.1) #plt.scatter(1.373,0.1175,marker='o',color='w',s=25) #plt.errorbar(1.373,0.035,xerr=0.048,ls='none',color='k',capsize=5,linewidth=1,alpha=0.5) #plt.errorbar(1.373,0.061,xerr=0.048,ls='none',color='k',capsize=5,linewidth=1,alpha=0.5) #plt.errorbar(1.373,0.106,xerr=0.048,ls='none',color='k',capsize=5,linewidth=1,alpha=0.5) #plt.axvline(1.373,linestyle='dashed',color='gray') plt.subplots_adjust(bottom=0.10, top=0.98, left=0.10, right=0.99) #for axis in ['top','bottom','left','right']: # plt.subplot(1,1,1).spines[axis].set_linewidth(1.5) plt.axes().set_aspect('auto') plt.savefig("r2vsm2_curr.pdf") plt.show()
def run_all_plots(): # # CEI timeseries if True: # from https://www.ncdc.noaa.gov/extremes/cei/graph/us/03-05/4 (Spring, Step4 indicator) cei = read_cei("CEI_step4_figure_data.csv") smoothed = binomialfilter(cei.data, -99.9, 9, pad=False) smoothed = np.ma.masked_where(smoothed == -99.9, smoothed) fig = plt.figure(figsize=(8, 5)) plt.clf() ax1 = plt.axes([0.11, 0.08, 0.86, 0.90]) ax1.bar(cei.times, cei.data, color="g", label=cei.name, align="center", width=1, edgecolor="darkgreen") ax1.plot(cei.times, smoothed, "r", lw=LW) ax1.plot([cei.times[0], cei.times[-1]], [np.mean(cei.data), np.mean(cei.data)], "k", lw=1) ax1.set_xlim([1910, int(settings.YEAR) + 2]) ax1.set_ylabel("%", fontsize=settings.FONTSIZE) minorLocator = MultipleLocator(1) ax1.xaxis.set_minor_locator(minorLocator) utils.thicken_panel_border(ax1) ax1.yaxis.set_tick_params(right=False) for tick in ax1.xaxis.get_major_ticks(): tick.label.set_fontsize(settings.FONTSIZE) for tick in ax1.yaxis.get_major_ticks(): tick.label.set_fontsize(settings.FONTSIZE) # ax1.text(0.02, 0.9, "(e)", transform=ax1.transAxes, fontsize=settings.FONTSIZE) plt.savefig(settings.IMAGELOC + "PEX_CEI_ts{}".format(settings.OUTFMT)) plt.close() #************************* # GHCNDEX indices rank_bounds = [-4.5, -3.5, -2.5, -1.5, 1.5, 2.5, 3.5, 4.5] if True: for index in ETCCDI_INDICES: cube_list = iris.load( DATALOC + "GHCND_{}_1951-{}_RegularGrid_global_2.5x2.5deg_LSmask.nc". format(index, int(settings.YEAR) + 1)) names = np.array([cube.name() for cube in cube_list]) #************* # plot annual map selected_cube, = np.where(names == "Ann") total_cube = cube_list[selected_cube[0]] total_cube.coord('latitude').guess_bounds() total_cube.coord('longitude').guess_bounds() anoms = copy.deepcopy(total_cube) anoms = ApplyClimatology(anoms) # select the year to plot years = GetYears(total_cube) loc, = np.where(years == SELECTED_YEAR) # sort the bounds and colourbars if index in ["Rx1day"]: bounds = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] cmap = settings.COLOURMAP_DICT["precip_sequential"] elif index in ["Rx5day"]: bounds = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180] cmap = settings.COLOURMAP_DICT["precip_sequential"] elif index in ["R10mm"]: bounds = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45] cmap = settings.COLOURMAP_DICT["precip_sequential"] elif index in ["R20mm"]: bounds = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45] cmap = settings.COLOURMAP_DICT["precip_sequential"] elif index in ["R95p"]: bounds = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225] cmap = settings.COLOURMAP_DICT["precip_sequential"] elif index in ["PRCPTOT"]: bounds = [0, 25, 50, 75, 100, 125, 150, 200, 300, 400] cmap = settings.COLOURMAP_DICT["precip_sequential"] utils.plot_smooth_map_iris( settings.IMAGELOC + "PEX_{}_{}_ghcndex".format(index, settings.YEAR), total_cube[loc[0]], cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), title="GHCNDEX {} - {}".format(index, ETCCDI_LABELS[index])) # sort the bounds and colourbars if index in ["Rx1day"]: bounds = [-100, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 100] bounds = [ -100, -40, -30, -20, -10, -5, 0, 5, 10, 20, 30, 40, 100 ] cmap = settings.COLOURMAP_DICT["hydrological"] elif index in ["Rx5day"]: bounds = [ -100, -40, -30, -20, -10, -5, 0, 5, 10, 20, 30, 40, 100 ] cmap = settings.COLOURMAP_DICT["hydrological"] elif index in ["R10mm"]: bounds = [-20, -8, -6, -4, -2, 0, 2, 4, 6, 8, 20] cmap = settings.COLOURMAP_DICT["hydrological"] elif index in ["R20mm"]: bounds = [-20, -4, -3, -2, -1, 0, 1, 2, 3, 4, 20] cmap = settings.COLOURMAP_DICT["hydrological"] elif index in ["R95p"]: bounds = [ -1000, -100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100, 1000 ] cmap = settings.COLOURMAP_DICT["hydrological"] elif index in ["PRCPTOT"]: bounds = [ -1000, -150, -80, -60, -40, -20, 0, 20, 40, 60, 80, 150, 1000 ] cmap = settings.COLOURMAP_DICT["hydrological"] utils.plot_smooth_map_iris( settings.IMAGELOC + "PEX_{}_{}_anoms_ghcndex".format(index, settings.YEAR), anoms[loc[0]], cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), title="GHCNDEX {} - {}".format(index, ETCCDI_LABELS[index])) if index == "Rx1day": utils.plot_smooth_map_iris( settings.IMAGELOC + "p2.1_PEX_{}_{}_anoms_ghcndex".format( index, settings.YEAR), anoms[loc[0]], cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), figtext="(k) Maximum 1 Day Precipitation Amount") rank_cube = get_ranks(anoms) plot_rank_map( settings.IMAGELOC + "PEX_{}_{}_rank_ghcndex".format(index, settings.YEAR), rank_cube[loc[0]], cmap, rank_bounds, "Rank", title="{} - {}".format(index, ETCCDI_UNITS[index])) #************* # plot season maps (2x2) if index in ["Rx1day", "Rx5day"]: for sc, cube in enumerate([total_cube, anoms]): season_list = [] for season in SEASONS: # extract each month month_data = [] months = SEASON_DICT[season] for month in months: selected_cube, = np.where(names == month) cube = cube_list[selected_cube[0]] if month == "Dec": # need to extract from previous year - cheat by rolling data around cube.data = np.roll(cube.data, 1, axis=0) cube.data.mask[ 0, :, :] = True # and mask out the previous years' month_data += [cube.data] # finished getting all months, make a dummy cube to populate month_data = np.ma.array(month_data) season_cube = copy.deepcopy(cube) # take appropriate seasonal value season_cube.data = np.ma.max(month_data, axis=0) # mask if fewer that 2 months present nmonths_locs = np.ma.count(month_data, axis=0) season_cube.data = np.ma.masked_where( nmonths_locs < 2, season_cube.data) # make anomalies if sc == 1: season_cube = ApplyClimatology(season_cube) # fix for plotting season_cube.coord('latitude').guess_bounds() season_cube.coord('longitude').guess_bounds() # select the year to plot years = GetYears(cube) loc, = np.where(years == SELECTED_YEAR) # add to list season_list += [season_cube[loc[0]]] # sort the bounds and colourbars if sc == 0: if index in ["Rx1day", "Rx5day"]: bounds = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] cmap = settings.COLOURMAP_DICT["precip_sequential"] # pass to plotting routine utils.plot_smooth_map_iris_multipanel( settings.IMAGELOC + "PEX_{}_{}_seasons_ghcndex".format( index, settings.YEAR), season_list, cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), shape=(2, 2), title=SEASONS, figtext=["(a)", "(b)", "(c)", "(d)"], figtitle="{} - {}".format(index, ETCCDI_LABELS[index])) elif sc == 1: cmap = settings.COLOURMAP_DICT["hydrological"] if index in ["Rx1day"]: bounds = [ -100, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 100 ] elif index in ["Rx5day"]: bounds = [ -100, -20, -16, -12, -8, -4, 0, 4, 8, 12, 16, 20, 100 ] # pass to plotting routine utils.plot_smooth_map_iris_multipanel( settings.IMAGELOC + "PEX_{}_{}_anoms_seasons_ghcndex".format( index, settings.YEAR), season_list, cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), shape=(2, 2), title=SEASONS, figtext=["(a)", "(b)", "(c)", "(d)"], figtitle="{} - {}".format(index, ETCCDI_LABELS[index])) #************************* # DWD indices if True: for index in DWD_INDICES: print(index) if not os.path.exists( DATALOC + "First_Guess_Daily_{}_{}.nc".format(settings.YEAR, index)): print("File {} missing".format( "First_Guess_Daily_{}_{}.nc".format(settings.YEAR, index))) continue cube_list = iris.load( DATALOC + "First_Guess_Daily_{}_{}.nc".format(settings.YEAR, index)) if len(cube_list) == 1: cube = cube_list[0] else: # these have two fields for cube in cube_list: if cube.units == "mm per 5 day" and index == "RX5": break elif cube.var_name == "consecutive_wet_days_index_per_time_period" and index == "CWD": break elif cube.var_name == "consecutive_dry_days_index_per_time_period" and index == "CDD": break else: print( "Check cube for {} for extra fields".format(index)) cube = cube[0] # take only single slice cube.coord('latitude').guess_bounds() cube.coord('longitude').guess_bounds() if index in ["CDD"]: bounds = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180] cmap = settings.COLOURMAP_DICT["precip_sequential_r"] elif index in ["CWD"]: bounds = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180] bounds = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] cmap = settings.COLOURMAP_DICT["precip_sequential"] elif index in ["DD"]: bounds = [0, 40, 80, 120, 160, 200, 240, 280, 320, 360] cmap = settings.COLOURMAP_DICT["precip_sequential_r"] elif index in ["PD"]: bounds = [0, 40, 80, 120, 160, 200, 240, 280, 320, 360] cmap = settings.COLOURMAP_DICT["precip_sequential"] elif index in ["RX1", "PD10"]: bounds = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] cmap = settings.COLOURMAP_DICT["precip_sequential"] elif index in ["RX5"]: bounds = [0, 50, 100, 150, 200, 250, 300, 350, 400, 450] bounds = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180] cmap = settings.COLOURMAP_DICT["precip_sequential"] elif index in ["R10", "R20", "R95P", "SDII", "PD20"]: bounds = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45] cmap = settings.COLOURMAP_DICT["precip_sequential"] utils.plot_smooth_map_iris( settings.IMAGELOC + "PEX_{}_{}_dwd".format(index, settings.YEAR), cube, cmap, bounds, "{} ({})".format(index, DWD_UNITS[index]), title="{} - {}".format(index, DWD_LABELS[index])) #************************* # DWD differences indices if True: for index in DWD_INDICES: print(index) if not os.path.exists( DATALOC + "Diff_{}-Mean_{}.nc".format(index, settings.YEAR)): print("File {} missing".format("Diff_{}-Mean_{}.nc".format( index, settings.YEAR))) continue cube_list = iris.load( DATALOC + "Diff_{}-Mean_{}.nc".format(index, settings.YEAR)) if len(cube_list) == 1: cube = cube_list[0] else: # these have two fields for cube in cube_list: if cube.units == "mm per 5 day" and index == "RX5": break cube = cube[0] # take only single slice cube.coord('latitude').guess_bounds() cube.coord('longitude').guess_bounds() if index in ["RX1"]: bounds = [-100, -50, -25, -10, -5, 0, 5, 10, 25, 50, 100] cmap = settings.COLOURMAP_DICT["hydrological"] elif index in ["RX5"]: bounds = [-50, -30, -20, -10, -5, 0, 5, 10, 20, 30, 50] bounds = [-100, -50, -25, -10, -5, 0, 5, 10, 25, 50, 100] cmap = settings.COLOURMAP_DICT["hydrological"] elif index in ["PD10", "PD20", "R95P"]: bounds = [-50, -30, -20, -10, -5, 0, 5, 10, 20, 30, 50] cmap = settings.COLOURMAP_DICT["hydrological"] utils.plot_smooth_map_iris( settings.IMAGELOC + "PEX_{}_{}_diff_dwd".format(index, settings.YEAR), cube, cmap, bounds, "Anomalies from 1982-2016 {} ({})".format( index, DWD_UNITS[index]), title="{} - {}".format(index, DWD_LABELS[index])) if index == "PD10": utils.plot_smooth_map_iris( settings.IMAGELOC + "p2.1_PEX_{}_{}_diff_dwd".format("R10mm", settings.YEAR), cube, cmap, bounds, "Anomalies from 1982-2016 {} ({})".format( "R10mm", ETCCDI_UNITS["R10mm"]), figtext="(l) {} anomalies".format("R10mm")) else: utils.plot_smooth_map_iris( settings.IMAGELOC + "p2.1_PEX_{}_{}_diff_dwd".format(index, settings.YEAR), cube, cmap, bounds, "Anomalies from 1982-2016 {} ({})".format( index, DWD_UNITS[index]), figtext="(l) {} anomalies".format(index)) #************************* # MERRA map if True: index = "R10mm" cube = iris.load(DATALOC + "MERRA2_ann_2019_r10mm_gl_anom.nc")[0] bounds = [-50, -30, -20, -10, -5, 0, 5, 10, 20, 30, 50] cmap = settings.COLOURMAP_DICT["hydrological"] utils.plot_smooth_map_iris( settings.IMAGELOC + "PEX_R10mm_{}_merra2".format(settings.YEAR), cube[0], cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), title="MERRA-2 {} - {}".format(index, ETCCDI_LABELS[index])) #************************* # ERA5 map if False: index = "Rx1day" cube = read_era5("prmax_{}.txt".format(settings.YEAR)) bounds = [0, 2, 5, 10, 20, 40, 80, 160, 300, 450] cmap = settings.COLOURMAP_DICT["precip_sequential"] utils.plot_smooth_map_iris( settings.IMAGELOC + "PEX_Rx1day_{}_era5".format(settings.YEAR), cube, cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), title="ERA5 {} - {}".format(index, ETCCDI_LABELS[index])) #************************* # ERA5 map if True: index = "Rx1day" cube = read_era5("prmax1d_anomaly_for_{}_wrt_1981-2010.txt".format( settings.YEAR)) bounds = [-400, -100, -75, -50, -25, 0, 25, 50, 75, 100, 400] bounds = [-400, -100, -50, -20, -10, 0, 10, 20, 50, 100, 400] bounds = [-100, -40, -30, -20, -10, -5, 0, 5, 10, 20, 30, 40, 100] cmap = settings.COLOURMAP_DICT["hydrological"] utils.plot_smooth_map_iris( settings.IMAGELOC + "PEX_Rx1day_{}_anoms_era5".format(settings.YEAR), cube, cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), title="ERA5 {} - {}".format(index, ETCCDI_LABELS[index])) # utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_PEX_Rx1day_{}_anoms_era5".format(settings.YEAR), cube, cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), figtext="(i) Rx1day anomalies") # cube = read_era5("prmax_for_{}_as_a_percentage_of_1981-2010_mean.txt".format(settings.YEAR)) # bounds = [0, 10, 25, 50, 75, 100, 150, 200, 250, 300, 1000] # cmap = settings.COLOURMAP_DICT["hydrological"] # utils.plot_smooth_map_iris(settings.IMAGELOC + "PEX_Rx1day_{}_anoms_percent_era5".format(settings.YEAR), cube, cmap, bounds, "Anomalies from 1981-2010 (%)", title="ERA5 - Rx1day %") # utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_PEX_Rx1day_{}_anoms_percent_era5".format(settings.YEAR), cube, cmap, bounds, "Anomalies from 1981-2010 (%)", figtext="(m) Rx1day anomalies") #************************* # DWD percentile if True: # dwd_cube = read_dwd_percentile(DATALOC + "GPCC_perzentile_{}.xyzras".format(settings.YEAR)) cube_list = iris.load(DATALOC + "Quantile_12month_{}01-{}12.nc".format( settings.YEAR, settings.YEAR)) dwd_cube = cube_list[0][0] bounds = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] cmap = settings.COLOURMAP_DICT["hydrological"] utils.plot_smooth_map_iris( settings.IMAGELOC + "PEX_{}_{}_dwd".format("R90", settings.YEAR), dwd_cube, cmap, bounds, "{} ({})".format("percentile", "%"), title="Percentile of the annual precipitation total") utils.plot_smooth_map_iris( settings.IMAGELOC + "p2.1_PEX_{}_{}_dwd".format("R90", settings.YEAR), dwd_cube, cmap, bounds, "{} ({})".format("percentile", "%"), figtext="(l) Percentile of the Annual Precipitation Total") #************************* # DWD drought if True: # dwd_cube = read_dwd_percentile(DATALOC + "GPCC_perzentile_{}.xyzras".format(settings.YEAR)) cube_list = iris.load(DATALOC + "GPCC_DI_201912_12.nc") dwd_cube = cube_list[0][0] bounds = [-10, -5, -3, -2, -1, 0, 1, 2, 3, 5, 10] cmap = settings.COLOURMAP_DICT["hydrological"] utils.plot_smooth_map_iris(settings.IMAGELOC + "PEX_{}_{}_dwd".format("DI", settings.YEAR), dwd_cube, cmap, bounds, "{} ({})".format("DI", "-"), title="12 month Drought Index") #************************* # GHCND totals and ratios if False: import cartopy.feature as cfeature NAMES = {"japan": "Japan", "neaus": "Australia", "hawaii": "Hawaii"} EXTENTS = { "japan": (132, 33, [126, 139, 30, 36]), "neaus": (145, -17, [139, 151, -26, -8]), "hawaii": (-158, 20, [-161, -154, 18.5, 22.5]) } land_10m = cfeature.NaturalEarthFeature( 'physical', 'land', '10m', edgecolor='face', facecolor=cfeature.COLORS['land']) land_50m = cfeature.NaturalEarthFeature( 'physical', 'land', '50m', edgecolor='face', facecolor=cfeature.COLORS['land']) for index in ["Rx5day", "Rx1day"]: for state in ["03-neaus", "07-japan", "08-hawaii"]: print("{} - {}".format(state, index)) lats, lons, value_mm, prev_value_mm = read_ghcnd( "{}/{}-{}-non0-sorted-{}.txt".format( DATALOC, index, settings.YEAR, state)) ratio = value_mm / prev_value_mm # set up figure if "neaus" in state: fig = plt.figure(figsize=(8, 5)) else: fig = plt.figure(figsize=(8, 3.5)) if index == "Rx5day": bounds = [0, 100, 200, 300, 400, 500, 600, 700, 800, 900] elif index == "Rx1day": bounds = [0, 50, 100, 150, 200, 250, 300, 350, 400, 450] cmap = settings.COLOURMAP_DICT["precip_sequential"] norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N) # ratio_cmap = plt.cm.YlOrRd # ratio_bounds = [1, 1.05, 1.1, 1.15, 1.2, 1.3, 1.5, 1.75, 2.0 ] # ratio_cmap = settings.COLOURMAP_DICT["hydrological"] # ratio_bounds = [0.01, 0.5, 0.75, 0.9, 0.95, 1.0, 1.05, 1.1, 1.25, 2.0, 10.0] ratio_cmap = plt.cm.Blues ratio_bounds = [ 0.01, 0.5, 0.7, 0.9, 1.0, 1.1, 1.3, 1.5, 2.0, 10.0 ] ratio_norm = mpl.cm.colors.BoundaryNorm( ratio_bounds, ratio_cmap.N) plt.clf() # set up axes ax0 = plt.axes([0.01, 0.12, 0.45, 0.85], projection=cartopy.crs.Stereographic( central_longitude=EXTENTS[state[3:]][0], central_latitude=EXTENTS[state[3:]][1])) ax1 = plt.axes([0.51, 0.12, 0.45, 0.85], projection=cartopy.crs.Stereographic( central_longitude=EXTENTS[state[3:]][0], central_latitude=EXTENTS[state[3:]][1])) for ax in [ax0, ax1]: ax.set_extent(EXTENTS[state[3:]][2], cartopy.crs.PlateCarree()) states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') ax.add_feature(states_provinces, edgecolor='gray') ax.coastlines(resolution="10m", linewidth=0.5) ax.add_feature(land_50m, zorder=0, facecolor="0.9", edgecolor="k") # add other features ax.gridlines() #draw_labels=True) ax.add_feature(cartopy.feature.BORDERS, zorder=0, facecolor="0.9", edgecolor="k") # plot for ax, data, cm, bnds, nrm, label in zip( [ax0, ax1], [value_mm, ratio], [cmap, ratio_cmap], [bounds, ratio_bounds], [norm, ratio_norm], ["{} (mm)".format(index), "Ratio to previous record"]): scatter = ax.scatter(lons, lats, c=data, cmap=cm, norm=nrm, s=50, \ transform=cartopy.crs.Geodetic(), edgecolor='0.5', linewidth=0.5) # thicken border of colorbar and the dividers # http://stackoverflow.com/questions/14477696/customizing-colorbar-border-color-on-matplotlib if "Ratio" in label: cb = fig.colorbar(scatter, ax=ax, orientation='horizontal', pad=0.05, fraction=0.05, \ aspect=30, ticks=bnds[1:-1], label=label, drawedges=True) cb.set_ticklabels( ["{:g}".format(b) for b in bnds[1:-1]]) else: cb = fig.colorbar(scatter, ax=ax, orientation='horizontal', pad=0.05, fraction=0.05, \ aspect=30, ticks=bnds[1:-1], label=label, drawedges=True) cb.set_ticklabels(["{:g}".format(b) for b in bnds]) cb.outline.set_linewidth(2) cb.dividers.set_color('k') cb.dividers.set_linewidth(2) cb.ax.tick_params(axis='x', labelsize=settings.FONTSIZE * 0.6, direction='in') if index == "Rx5day" and state[3:] == "hawaii": ax0.text(0.05, 1.05, "(a)", transform=ax0.transAxes, fontsize=settings.FONTSIZE * 0.8) ax1.text(0.05, 1.05, "(b)", transform=ax1.transAxes, fontsize=settings.FONTSIZE * 0.8) elif index == "Rx1day" and state[3:] == "hawaii": ax0.text(0.05, 1.05, "(c)", transform=ax0.transAxes, fontsize=settings.FONTSIZE * 0.8) ax1.text(0.05, 1.05, "(d)", transform=ax1.transAxes, fontsize=settings.FONTSIZE * 0.8) plt.savefig( settings.IMAGELOC + "PEX_{}_{}-{}".format(index, NAMES[state[3:]], state[:2]) + settings.OUTFMT) plt.close() return # run_all_plots
EASING_1 = np.datetime64('2021-07-28') LOCKDOWN_AGAIN = np.datetime64('2021-08-06') CURFEW = np.datetime64('2021-08-16') CONSTRUCTION_SHUTDOWN = np.datetime64('2021-09-21') END_CONSTRUCTION_SHUTDOWN = CONSTRUCTION_SHUTDOWN + 14 PHASE_B = np.datetime64('2021-10-22') PHASE_C = np.datetime64('2021-10-30') PHASE_D = np.datetime64('2021-11-19') MASKS_AGAIN = np.datetime64('2021-12-24') DENSITY_LIMITS = np.datetime64('2022-01-07') END_DENSITY_LIMITS = np.datetime64('2022-02-19') END_MASKS = np.datetime64('2022-02-26') fig1 = plt.figure(figsize=(10, 6)) ax1 = plt.axes() ax1.fill_betweenx( [-10, 10], [PREV_LOCKDOWN, PREV_LOCKDOWN], [PREV_EASING_1, PREV_EASING_1], color=whiten("red", 0.35), linewidth=0, label="Lockdown", ) ax1.fill_betweenx( [-10, 10], [PREV_EASING_1, PREV_EASING_1], [PREV_EASING_2, PREV_EASING_2], color=whiten("orange", 0.5),
def run(self): """ runs the segment picker """ # show the images self.fig, self.axes = plt.subplots(nrows=1, ncols=2, sharex=True, sharey=True, squeeze=True) plt.subplots_adjust(bottom=0.2) ax_img, ax_feat = self.axes imshow_args = { 'interpolation': 'none', 'aspect': 1, 'cmap': plt.get_cmap('gray') } ax_img.imshow(self._frame, **imshow_args) ax_img.set_title('First _frame of video') ax_img.set_autoscale_on(False) ax_feat.imshow(self.features, **imshow_args) ax_feat.set_title('Automatic feature extraction') ax_feat.set_autoscale_on(False) # internal data self.active = True self.result = 'cancel' self.bounds = self._frame.shape self._ax_segments = [[] for _ in xrange(len(self.axes))] # initialize data if self.segments: segments = self.segments self.segments = [] for segment in segments: self._add_segment(segment) # drawtype is 'box' or 'line' or 'none' useblit = backend.supports_blitting() self.selectors = [ widgets.RectangleSelector( ax, self.select_callback, drawtype='line', lineprops=self.lineprops, useblit=useblit, button=[1], # don't use middle button minspanx=5, minspany=5, spancoords='pixels') for ax in (ax_img, ax_feat) ] # add buttons ax_active = plt.axes([0.5, 0.05, 0.1, 0.075]) check = widgets.CheckButtons(ax_active, ['active'], [self.active]) check.on_clicked(self.clicked_check) ax_ok = plt.axes([0.7, 0.05, 0.1, 0.075]) bn_ok = widgets.Button(ax_ok, 'Ok') bn_ok.on_clicked(self.clicked_ok) ax_cancel = plt.axes([0.81, 0.05, 0.1, 0.075]) bp_cancel = widgets.Button(ax_cancel, 'Cancel') bp_cancel.on_clicked(self.clicked_cancel) self.msg() # initialize the interaction with the image self.fig.canvas.mpl_connect('button_press_event', self.click_image) # process result plt.show() return self.result
except: raise import networkx as nx z=nx.create_degree_sequence(400,nx.utils.powerlaw_sequence,exponent=2.1) nx.is_valid_degree_sequence(z) print "Configuration model" G=nx.configuration_model(z) # configuration model degree_sequence=sorted(nx.degree(G),reverse=True) # degree sequence #print "Degree sequence", degree_sequence dmax=max(degree_sequence) plt.loglog(degree_sequence,'b-',marker='o') plt.title("Degree rank plot") plt.ylabel("degree") plt.xlabel("rank") # draw graph in inset plt.axes([0.45,0.45,0.45,0.45]) Gcc=nx.connected_component_subgraphs(G)[0] pos=nx.spring_layout(Gcc) plt.axis('off') nx.draw_networkx_nodes(Gcc,pos,node_size=20) nx.draw_networkx_edges(Gcc,pos,alpha=0.4) plt.show()
import numpy as np import matplotlib.pyplot as plt def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2) n = 10 x = np.linspace(-3,3,4*n) y = np.linspace(-3,3,3*n) X,Y = np.meshgrid(x,y) Z = f(X, Y) plt.axes([0.025, 0.025, 0.95, 0.95]) plt.imshow(Z, interpolation='bicubic', cmap='bone', origin='lower') plt.colorbar(shrink=.8) plt.xticks([]), plt.yticks([]) plt.show()
def plot_rank_map(outname, cube, cmap, bounds, cb_label, scatter=[], figtext="", title=""): ''' Standard scatter map :param str outname: output filename root :param array cube: cube to plot :param obj cmap: colourmap to use :param array bounds: bounds for discrete colormap :param str cb_label: colorbar label ''' norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N) fig = plt.figure(figsize=(8, 5.5)) plt.clf() ax = plt.axes([0.01, 0.12, 0.98, 0.88], projection=cartopy.crs.Robinson()) ax.gridlines() #draw_labels=True) ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor="0.9", edgecolor="k") ax.coastlines() ext = ax.get_extent() # save the original extent mesh = iris.plot.pcolormesh(cube, cmap=cmap, norm=norm) if len(scatter) > 0: lons, lats, data = scatter plt.scatter(lons, lats, c=data, cmap=cmap, norm=norm, s=25, \ transform=cartopy.crs.Geodetic(), edgecolor='0.5', linewidth=0.5) cb = plt.colorbar(mesh, orientation='horizontal', pad=0.05, fraction=0.05, \ aspect=30, ticks=bounds[1:-1], drawedges=True) # thicken border of colorbar and the dividers # http://stackoverflow.com/questions/14477696/customizing-colorbar-border-color-on-matplotlib cb.set_ticklabels(["{:g}".format(b) for b in bounds[1:-1]]) cb.ax.tick_params(axis='x', labelsize=settings.FONTSIZE, direction='in', size=0) cb.set_label(label=cb_label, fontsize=settings.FONTSIZE) # cb.outline.set_color('k') cb.outline.set_linewidth(2) cb.dividers.set_color('k') cb.dividers.set_linewidth(2) # label colorbar with sensibly placed and named labels cb.ax.get_xaxis().set_ticks([]) cb.ax.get_xaxis().set_ticklabels([""]) for j, lab in enumerate([ 'lowest', '2nd lowest', '3rd lowest', '', '3rd highest', '2nd highest', 'highest' ]): cb.ax.text((2 * j + 1) / 14.0, -0.5, lab, ha='center', va='center', fontsize=settings.FONTSIZE * 0.8) ax.set_extent(ext, ax.projection) # fix the extent change from colormesh plt.title(title) fig.text(0.03, 0.95, figtext, fontsize=settings.FONTSIZE) plt.savefig(outname + settings.OUTFMT) plt.close() return # plot_rank_map_iris
import serial from matplotlib import pyplot as plt from matplotlib import animation import numpy as np import time arduino = serial.Serial('COM3', 9600) time.sleep(1) fig = plt.figure() ax = plt.axes(xlim=(0, 10), ylim=(24, 26)) max_points = 10 # fill initial artist with nans (so nothing draws) line, = ax.plot(np.arange(max_points), np.ones(max_points, dtype=np.float) * np.nan, lw=2) def init(): return line, def animate(i): rawString = arduino.readline() y = float(rawString.decode()) # I assume this y = (1.1 * y * 100) / 1024 print(y) old_y = line.get_ydata() # grab current data
fig = plt.figure() nframes = predict.shape[0] predict = np.reshape(predict, [nframes, -1, 3]) scats = [] lns = [] for j in frames: joint_xyz = np.squeeze(predict[j, :, :]) x_data = joint_xyz[:, 0] y_data = joint_xyz[:, 1] z_data = joint_xyz[:, 2] ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax), zlim=(zmin, zmax), projection='3d') ax.set_axis_off() ax.view_init(azim=10, elev=60) plt.gca().set_aspect('equal', adjustable='box') ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.set_yticklabels([]) ax.set_xticklabels([]) ax.set_zticklabels([]) lns.append( ax.plot3D(x_data[chain[:]], y_data[chain[:]],