def click(self,event): """ What to do, if a click on the figure happens: 1. Check which axis 2. Get data coord's. 3. Plot resulting data. 4. Update Figure """ if event.inaxes==self.overview: #Get nearest data xpos=np.argmin(np.abs(event.xdata-self.x)) ypos=np.argmin(np.abs(event.ydata-self.y)) #Check which mouse button: if event.button==1: #Plot it c,=self.y_subplot.plot(self.y, self.z[:,xpos],label=str(self.x[xpos])) self.overview.axvline(self.x[xpos],color=c.get_color(),lw=2) elif event.button==3: #Plot it c,=self.x_subplot.plot(self.x, self.z[ypos,:],label=str(self.y[ypos])) self.overview.axhline(self.y[ypos],color=c.get_color(),lw=2) if event.inaxes==self.y_subplot: ypos=np.argmin(np.abs(event.xdata-self.y)) c=self.x_subplot.plot(self.x, self.z[ypos,:],label=str(self.y[ypos])) self.overview.axhline(self.y[ypos],color=c.get_color(),lw=2) if event.inaxes==self.x_subplot: xpos=np.argmin(np.abs(event.xdata-self.x)) c,=self.y_subplot.plot(self.y, self.z[:,xpos],label=str(self.x[xpos])) self.overview.axvline(self.x[xpos],color=c.get_color(),lw=2) #Show it plt.draw()
def vis_detections (im, class_name, dets, thresh=0.5): """Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0: return im = im[:, :, (2, 1, 0)] fig, ax = plt.subplots(figsize=(12, 12)) ax.imshow(im, aspect='equal') for i in inds: bbox = dets[i, :4] score = dets[i, -1] ax.add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=3.5) ) ax.text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') ax.set_title(('{} detections with ' 'p({} | box) >= {:.1f}').format(class_name, class_name, thresh), fontsize=14) plt.axis('off') plt.tight_layout() plt.draw()
def plot_marginal_pdfs( res, nbins=101, **kwargs): """ plot the results of a classification run :return: """ from matplotlib import pyplot as pl import numpy as np nparam = len(res.vparam_names) # nrow = np.sqrt( nparam ) # ncol = nparam / nrow + 1 nrow, ncol = 1, nparam pdfdict = get_marginal_pdfs( res, nbins ) fig = pl.gcf() for parname in res.vparam_names : iax = res.vparam_names.index( parname )+1 ax = fig.add_subplot( nrow, ncol, iax ) parval, pdf, mean, std = pdfdict[parname] ax.plot( parval, pdf, **kwargs ) if np.abs(std)>=0.1: ax.text( 0.95, 0.95, '%s %.1f +- %.1f'%( parname, np.round(mean,1), np.round(std,1)), ha='right',va='top',transform=ax.transAxes ) elif np.abs(std)>=0.01: ax.text( 0.95, 0.95, '%s %.2f +- %.2f'%( parname, np.round(mean,2), np.round(std,2)), ha='right',va='top',transform=ax.transAxes ) elif np.abs(std)>=0.001: ax.text( 0.95, 0.95, '%s %.3f +- %.3f'%( parname, np.round(mean,3), np.round(std,3)), ha='right',va='top',transform=ax.transAxes ) else : ax.text( 0.95, 0.95, '%s %.3e +- %.3e'%( parname, mean, std), ha='right',va='top',transform=ax.transAxes ) pl.draw()
def hist(nndist, **kwds): if 'output' in kwds: import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt # handle formatting keywords linewidth = kwds.get('linewidth', 3) #plt.rc('text', usetex=True) plt.rc('font', family='serif') n, bins, patches = plt.hist(nndist, normed=True, bins=100) width = bins[1] - bins[0] ax1 = plt.gca() ax2 = plt.twinx() ax2.plot(bins[:-1], width*np.cumsum(n), 'r-', linewidth=linewidth) ax2.set_ylim(top=1.0) tics = ax1.get_yticks(); ax1.set_yticks(tics[1:]) tics = ax2.get_yticks(); ax2.set_yticks(tics[1:]) ax1.set_xlabel(r"d ($\mu$m)") ax1.set_ylabel(r"PDF") ax2.set_ylabel(r"CDF", color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') # check scalar descriptors median_dist = np.median(nndist) ax1.axvline(median_dist, color='gray', linewidth=linewidth) # handle keywords if 'title' in kwds: plt.title(kwds['title']) if 'output' in kwds: plt.draw() plt.savefig(kwds['output']) else: plt.show()
def Update(self, iter): #Update the scatter plot next(self.DoTimeSteps()) self.scat._offsets3d = ( np.ma.ravel(self.r[0,:]) , np.ma.ravel(self.r[1,:]) , np.ma.ravel(self.r[2,:]) ) self.time.append(iter*self.dt) #Update the energy plot every 25th iteration step if iter%25==0: self.plEkin.set_data(self.time, self.Ekin) self.plVtot.set_data(self.time, self.Vtot) self.plEtot.set_data(self.time, self.Etot) self.plEkin.axes.set_xlim(0, self.time[-1]) self.plVtot.axes.set_xlim(0, self.time[-1]) self.plEtot.axes.set_xlim(0, self.time[-1]) #Update the scale of the energy plot and add the structure factor data every 100th iteration step if (iter-10)%100==0: miny = min([min(self.Ekin), min(self.Vtot), min(self.Etot)]) maxy = max([max(self.Ekin), max(self.Vtot), max(self.Etot)]) self.plEkin.axes.set_ylim(miny, maxy) self.plVtot.axes.set_ylim(miny, maxy) self.plEtot.axes.set_ylim(miny, maxy) r2, histo = self.GetGr() GrNew = np.zeros((self.bins,1)) for i in range(len(GrNew)): GrNew[i,0]=histo[i] self.Gr = np.concatenate((self.Gr,GrNew), axis=1) plt.draw() return self.scat, self.plEkin, self.plVtot, self.plEtot
def write(self, timestamps, actualValues, predictedValues, predictionStep=1): assert len(timestamps) == len(actualValues) == len(predictedValues) # We need the first timestamp to initialize the lines at the right X value, # so do that check first. if not self.linesInitialized: self.initializeLines(timestamps) for index in range(len(self.names)): self.dates[index].append(timestamps[index]) self.convertedDates[index].append(date2num(timestamps[index])) self.actualValues[index].append(actualValues[index]) self.predictedValues[index].append(predictedValues[index]) # Update data self.actualLines[index].set_xdata(self.convertedDates[index]) self.actualLines[index].set_ydata(self.actualValues[index]) self.predictedLines[index].set_xdata(self.convertedDates[index]) self.predictedLines[index].set_ydata(self.predictedValues[index]) self.graphs[index].relim() self.graphs[index].autoscale_view(True, True, True) plt.draw() plt.legend(('actual','predicted'), loc=3)
def update(self, analogData): ticks = range(len(analogData.az))[0::int(len(analogData.az)/5)] myticks = list(analogData.az[i] for i in xrange(0, len(analogData.az),int(len(analogData.az)/4))) self.plt.xticks(ticks, myticks) self.axline.set_ydata(analogData.ax) self.ayline.set_ydata(analogData.ay) plt.draw()
def accuracy(target, prediction, label="Classifier", c=np.zeros((0,0))): correct = (target == prediction) correct = np.array((correct, correct)) compare = np.array((target, prediction)) showC = c != np.zeros((0,0)) if (showC): fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10)) else: fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(6,8)) dim = [0,compare.shape[1],0,compare.shape[0]] ax1.imshow(compare, extent=dim, aspect='auto', interpolation='nearest') ax1.set_title(label + ": Prediction vs. Target") imgPlt = ax2.imshow(correct, extent=dim, aspect='auto', interpolation='nearest') imgPlt.set_cmap('RdYlGn') ax2.set_title(label + " Prediction Accuracy") if (showC): ax3.plot(c) ax3.set_title("Concentration") ax3.set_yscale('log') ax3.set_ylim(0.02,0.7) plt.draw()
def test_axis_artist(): global axisline #self._axislines[loc] = new_fixed_axis(loc=loc, axes=axes) from mpl_toolkits.axes_grid.axislines import AxisArtistHelperRectlinear fig = plt.figure(1) fig.clf() ax=fig.add_subplot(111) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) if 1: _helper = AxisArtistHelperRectlinear.Fixed(ax, loc="left") axisline = AxisArtist(ax, _helper, offset=None, axis_direction="left") ax.add_artist(axisline) _helper = AxisArtistHelperRectlinear.Fixed(ax, loc="right") axisline = AxisArtist(ax, _helper, offset=None, axis_direction="right") ax.add_artist(axisline) _helper = AxisArtistHelperRectlinear.Fixed(ax, loc="bottom") axisline = AxisArtist(ax, _helper, offset=None, axis_direction="bottom") axisline.set_label("TTT") #axisline.label.set_visible(False) ax.add_artist(axisline) #axisline.major_ticklabels.set_axis_direction("bottom") axisline.major_ticks.set_tick_out(False) ax.set_ylabel("Test") axisline.label.set_pad(5) plt.draw()
def main(): conn = krpc.connect() vessel = conn.space_center.active_vessel streams = init_streams(conn,vessel) print vessel.control.throttle plt.axis([0, 100, 0, .1]) plt.ion() plt.show() t0 = time.time() timeSeries = [] vessel.control.abort = False while not vessel.control.abort: t_now = time.time()-t0 tel = Telemetry(streams,t_now) timeSeries.append(tel) timeSeriesRecent = timeSeries[-40:] plt.cla() plt.semilogy([tel.t for tel in timeSeriesRecent], [norm(tel.angular_velocity) for tel in timeSeriesRecent]) #plt.semilogy([tel.t for tel in timeSeriesRecent[1:]], [quat_diff_test(t1,t2) for t1,t2 in zip(timeSeriesRecent,timeSeriesRecent[1:])]) #plt.axis([t_now-6, t_now, 0, .1]) plt.draw() plt.pause(0.0000001) #time.sleep(0.0001) with open('log.json','w') as f: f.write(json.dumps([tel.__dict__ for tel in timeSeries],indent=4)) print 'The End'
def on_keypress(self,event): global colmax global colmin if event.key in ['1', '2', '3', '4', '5', '6', '7','8', '9', '0']: if not os.path.exists(write_dir + runtag): os.mkdir(write_dir + runtag) recordtag = write_dir + runtag + "/" + runtag + "_" + event.key + ".txt" print "recording filename in " + recordtag f = open(recordtag, 'a+') f.write(self.filename+"\n") f.close() if event.key == 'p': if not os.path.exists(write_dir + runtag): os.mkdir(write_dir + runtag) pngtag = write_dir + runtag + "/%s.png" % (self.filename) print "saving image as " + pngtag P.savefig(pngtag) if event.key == 'e': if not os.path.exists(write_dir + runtag): os.mkdir(write_dir + runtag) epstag = write_dir + runtag + "/%s.eps" % (self.filename) print "saving image as " + epstag P.savefig(epstag, format='eps') if event.key == 'r': colmin = self.inarr.min() colmax = self.inarr.max() P.clim(colmin, colmax) P.draw()
def demo(): fig1 = plt.figure(1, (6, 6)) fig1.clf() # PLOT 1 # simple image & colorbar ax = fig1.add_subplot(2, 2, 1) demo_simple_image(ax) # PLOT 2 # image and colorbar whose location is adjusted in the drawing time. # a hard way demo_locatable_axes_hard(fig1) # PLOT 3 # image and colorbar whose location is adjusted in the drawing time. # a easy way ax = fig1.add_subplot(2, 2, 3) demo_locatable_axes_easy(ax) # PLOT 4 # two images side by side with fixed padding. ax = fig1.add_subplot(2, 2, 4) demo_images_side_by_side(ax) plt.draw() plt.show()
def restart(arg): global collection, all_lines, all_nodes, points, done, nodes_ip4s, nodes_ip6s, lats, lons, cities, xys, colors if done: return for l in all_lines: l.remove() del l all_lines = [] all_nodes = NodeSet() nodes_ip4s = {} nodes_ip6s = {} lats = [] lons = [] cities=[] xys = [] colors = [] if collection: collection.remove() del collection collection = None for p in points: p.remove() del p points = [] print(arg) start_h = InfoHash() start_h.setBit(159, 1) step(start_h, 0) plt.draw()
def catchPotentiometry(ser, PGA_gain): i = 0 voltage = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] t = ["0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0"] pH = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] while True: line = ser.readline() if line == b'@DONE\n': print('Experiment complete') break elif line == b'B\n': pass else: try: s, ms, v = struct.unpack('<HHix', line) v = ADCtomV(v, PGA_gain) voltage.append(v) pH.append(0.0169*v+6.9097) t.append("{}:{}".format(s,ms)) plt.clf() plt.plot(pH[-50:-1]) plt.draw() plt.pause(0.00000001) except: pass
def test_contains(): import matplotlib.backend_bases as mbackend fig = plt.figure() ax = plt.axes() mevent = mbackend.MouseEvent( 'button_press_event', fig.canvas, 0.5, 0.5, 1, None) xs = np.linspace(0.25, 0.75, 30) ys = np.linspace(0.25, 0.75, 30) xs, ys = np.meshgrid(xs, ys) txt = plt.text( 0.48, 0.52, 'hello world', ha='center', fontsize=30, rotation=30) # uncomment to draw the text's bounding box # txt.set_bbox(dict(edgecolor='black', facecolor='none')) # draw the text. This is important, as the contains method can only work # when a renderer exists. plt.draw() for x, y in zip(xs.flat, ys.flat): mevent.x, mevent.y = plt.gca().transAxes.transform_point([x, y]) contains, _ = txt.contains(mevent) color = 'yellow' if contains else 'red' # capture the viewLim, plot a point, and reset the viewLim vl = ax.viewLim.frozen() ax.plot(x, y, 'o', color=color) ax.viewLim.set(vl)
def polim(axe, polluant='O3'): """ Raccourcis pour tracer les lignes horizontales décrivant les seuils réglementaires pour les polluants """ seuils = {'O3': (150, 180, 240), 'NO2': (135, 200, 400), 'SO2': (200, 300, 500)} labs = ['MVR', 'IR', 'A'] if polluant not in seuils.keys(): return axe colors = ('green', 'orange', 'red') xlim = axe.get_xlim() for i in range(len(seuils[polluant])): seuil = seuils[polluant][i] color = colors[i] x0 = xlim[0] x1 = xlim[1] axe.hlines(seuil, x0, x1, color, label='_nolegend_') for i in range(len(seuils[polluant])): # Deuxième passe pour inscrire les # valeurs, sinon le texte de la première ligne est décalée (bug MPL??) seuil = seuils[polluant][i] color = colors[i] x0 = xlim[0] t = "%s (%s)" % (labs[i], seuil) plt.text(x0, seuil, t, color=color, ha='left', va='bottom', weight='bold') plt.ylim(0, seuils[polluant][-1] + 100) plt.draw() return axe
def plot(self): if self.pos == None: self.pos = nx.graphviz_layout(self) NODE_SIZE = 500 plt.clf() nx.draw_networkx_nodes(self, pos=self.pos, nodelist=self.normal, node_color=NORMAL_COLOR, node_size=NODE_SIZE) nx.draw_networkx_nodes(self, pos=self.pos, nodelist=self.contam, node_color=CONTAM_COLOR, node_size=NODE_SIZE) nx.draw_networkx_nodes(self, pos=self.pos, nodelist=self.immune, node_color=IMMUNE_COLOR, node_size=NODE_SIZE) nx.draw_networkx_nodes(self, pos=self.pos, nodelist=self.dead, node_color=DEAD_COLOR, node_size=NODE_SIZE) nx.draw_networkx_edges(self, pos=self.pos, edgelist=self.nondead_edges(), width=2, edge_color='0.2') nx.draw_networkx_labels(self, pos=self.pos, font_color='0.95', font_size=11) plt.gca().get_xaxis().set_visible(False) plt.gca().get_yaxis().set_visible(False) plt.draw()
def _plot_histogram(self, data, number_of_devices=1, preamp_timeout=1253): if number_of_devices == 0: return data = np.array(data) plt.figure(3) plt.ioff() plt.get_current_fig_manager().window.wm_geometry("800x550+700+25") plt.clf() if number_of_devices == 1: plt.hist(data[0,:], bins=preamp_timeout, range=(1, preamp_timeout-1), color='b') elif number_of_devices == 2: plt.hist(data[0,:], bins=preamp_timeout, range=(1, preamp_timeout-1), color='r', label='JPM A') plt.hist(data[1,:], bins=preamp_timeout, range=(1, preamp_timeout-1), color='b', label='JPM B') plt.legend() elif number_of_devices > 2: raise Exception('Histogram plotting for more than two ' + 'devices is not implemented.') plt.xlabel('Timing Information [Preamp Time Counts]') plt.ylabel('Counts') plt.xlim(0, preamp_timeout) plt.draw() plt.pause(0.05)
def task3(fn_t, fn_tmdt, c): '''demonstration''' L = 1000 #length, using boundary condition u(x+L)=u(x) dx = 1. dt = 0.5 t_max = 100 #c = -10 b = (c*dt/dx)**2 #init fields x = arange(0,L+dx/2.,dx) #[0, .... , L], consider 0 = L #starting conditions field_t = fn_t(x,dt) #starting condition at t0 field_tmdt = fn_tmdt(x,dt) #starting condition at t0-dt eq1 = wave_eq_simple(field_t, field_tmdt, b) plt.ion() plot, = plt.plot(x, field_t) for t in arange(0,t_max,dt): print 'outer loop, t=',t eq1.step() plot.set_ydata(eq1.u) plt.draw()
def task1(): '''demonstration''' #TASK 0: Demo L = 1000 #length, using boundary condition u(x+L)=u(x) dx = 1. dt = 0.1 t_max = 100 c = +10 b = (c*dt/dx)**2 #init fields x = arange(0,L+dx/2.,dx) #[0, .... , L], consider 0 = L #starting conditions field_t = exp(-(x-10)**2) #starting condition at t0 field_tmdt = exp(-(x-c*dt-10)**2) #starting condition at t0-dt eq1 = wave_eq(field_t, field_tmdt, b) plt.ion() plot, = plt.plot(x, field_t) for t in arange(0,t_max,dt): print 'outer loop, t=',t eq1.step() plot.set_ydata(eq1.u) plt.draw()
def plotFFT(self): # Generates plot of the FFT output. To view, run plotFFT.py in a separate terminal figure1 = plt.figure(num= None, figsize=(12,12), dpi=80, facecolor='w', edgecolor='w') plot1 = figure1.add_subplot(111) line1, = plot1.plot( np.arange(0,512,0.5), np.zeros(1024), 'g-') plt.xlabel('freq (MHz)',fontsize = 12) plt.ylabel('Amplitude',fontsize = 12) plt.title('Pre-mixer FFT',fontsize = 12) plt.xticks(np.arange(0,512,50)) plt.xlim((0,512)) plt.grid() plt.show(block = False) count = 0 stop = 1.0e6 while(count < stop): overflow = np.fromstring(self.fpga.read('overflow', 4), dtype = '>B') print overflow self.fpga.write_int('fft_snap_ctrl',0) self.fpga.write_int('fft_snap_ctrl',1) fft_snap = (np.fromstring(self.fpga.read('fft_snap_bram',(2**9)*8),dtype='>i2')).astype('float') I0 = fft_snap[0::4] Q0 = fft_snap[1::4] I1 = fft_snap[2::4] Q1 = fft_snap[3::4] mag0 = np.sqrt(I0**2 + Q0**2) mag1 = np.sqrt(I1**2 + Q1**2) fft_mags = np.hstack(zip(mag0,mag1)) plt.ylim((0,np.max(fft_mags) + 300.)) line1.set_ydata((fft_mags)) plt.draw() count += 1
def test_contourf_transform_path_counting(): ax = plt.axes(projection=ccrs.Robinson()) plt.draw() # Capture the size of the cache before our test. gc.collect() initial_cache_size = len(cgeoaxes._PATH_TRANSFORM_CACHE) path_to_geos_counter = CallCounter(cartopy.mpl.patch, 'path_to_geos') with path_to_geos_counter: x, y, z = sample_data((30, 60)) cs = plt.contourf(x, y, z, 5, transform=ccrs.PlateCarree()) n_geom = sum([len(c.get_paths()) for c in cs.collections]) del cs if not six.PY3: del c plt.draw() # Before the performance enhancement, the count would have been 2 * n_geom, # but should now be just n_geom. msg = ('The given geometry was transformed too many times (expected: %s; ' 'got %s) - the caching is not working.' '' % (n_geom, path_to_geos_counter.count)) assert path_to_geos_counter.count == n_geom, msg # Check the cache has an entry for each geometry. assert len(cgeoaxes._PATH_TRANSFORM_CACHE) == initial_cache_size + n_geom # Check that the cache is empty again once we've dropped all references # to the source paths. plt.clf() gc.collect() assert len(cgeoaxes._PATH_TRANSFORM_CACHE) == initial_cache_size plt.close()
def __init__(self, xv, yv, mask, **kwargs): assert xv.shape == yv.shape, 'xv and yv must have the same shape' for dx, dq in zip(xv.shape, mask.shape): assert dx==dq+1, \ '''xv and yv must be cell verticies (i.e., one cell bigger in each dimension)''' self.xv = xv self.yv = yv self.mask = mask land_color = kwargs.pop('land_color', (0.6, 1.0, 0.6)) sea_color = kwargs.pop('sea_color', (0.6, 0.6, 1.0)) cm = plt.matplotlib.colors.ListedColormap([land_color, sea_color], name='land/sea') self._pc = plt.pcolor(xv, yv, mask, cmap=cm, vmin=0, vmax=1, **kwargs) self._xc = 0.25*(xv[1:,1:]+xv[1:,:-1]+xv[:-1,1:]+xv[:-1,:-1]) self._yc = 0.25*(yv[1:,1:]+yv[1:,:-1]+yv[:-1,1:]+yv[:-1,:-1]) if isinstance(self.xv, np.ma.MaskedArray): self._mask = mask[~self._xc.mask] else: self._mask = mask.flatten() plt.connect('button_press_event', self._on_click) plt.connect('key_press_event', self._on_key) self._clicking = False plt.title('Editing %s -- click "e" to toggle' % self._clicking) plt.draw()
def plotPSD(self, chan, time_interval): Npackets = np.int(time_interval * self.accum_freq) plot_range = (Npackets / 2) + 1 figure = plt.figure(num= None, figsize=(12,12), dpi=80, facecolor='w', edgecolor='w') # I plt.suptitle('Channel ' + str(chan) + ' , Freq = ' + str((self.freqs[chan] + self.LO_freq)/1.0e6) + ' MHz') plot1 = figure.add_subplot(311) plot1.set_xscale('log') plot1.set_autoscale_on(True) plt.ylim((-160,-80)) plt.title('I') line1, = plot1.plot(np.linspace(0, self.accum_freq/2., (Npackets/2) + 1), np.zeros(plot_range), label = 'I', color = 'green', linewidth = 1) plt.grid() # Q plot2 = figure.add_subplot(312) plot2.set_xscale('log') plot2.set_autoscale_on(True) plt.ylim((-160,-80)) plt.title('Q') line2, = plot2.plot(np.linspace(0, self.accum_freq/2., (Npackets/2) + 1), np.zeros(plot_range), label = 'Q', color = 'red', linewidth = 1) plt.grid() # Phase plot3 = figure.add_subplot(313) plot3.set_xscale('log') plot3.set_autoscale_on(True) plt.ylim((-120,-70)) #plt.xlim((0.0001, self.accum_freq/2.)) plt.title('Phase') plt.ylabel('dBc rad^2/Hz') plt.xlabel('log Hz') line3, = plot3.plot(np.linspace(0, self.accum_freq/2., (Npackets/2) + 1), np.zeros(plot_range), label = 'Phase', color = 'black', linewidth = 1) plt.grid() plt.show(block = False) count = 0 stop = 1.0e10 while count < stop: Is, Qs, phases = self.get_stream(chan, time_interval) I_mags = np.fft.rfft(Is, Npackets) Q_mags = np.fft.rfft(Is, Npackets) phase_mags = np.fft.rfft(phases, Npackets) I_vals = (np.abs(I_mags)**2 * ((1./self.accum_freq)**2 / (1.0*time_interval))) Q_vals = (np.abs(Q_mags)**2 * ((1./self.accum_freq)**2 / (1.0*time_interval))) phase_vals = (np.abs(phase_mags)**2 * ((1./self.accum_freq)**2 / (1.0*time_interval))) phase_vals = 10*np.log10(phase_vals) phase_vals -= phase_vals[0] #line1.set_ydata(Is) #line2.set_ydata(Qs) #line3.set_ydata(phases) line1.set_ydata(10*np.log10(I_vals)) line2.set_ydata(10*np.log10(Q_vals)) line3.set_ydata(phase_vals) plot1.relim() plot1.autoscale_view(True,True,False) plot2.relim() plot2.autoscale_view(True,True,False) #plot3.relim() plot3.autoscale_view(True,True,False) plt.draw() count +=1 return
def draw_window(): mutex.acquire() plt.clf() ax = plt.subplot(1,1,1) ax.plot(ub_times, ub_points, label = "Upper Bound" ) ax.plot(lb_times, lb_points, label = "Lower Bound" ) ax.plot(corrected_points_times, corrected_points, label="Estimate") ax.plot(ub_times_matched, ub_points_matched, label="Matched Upper Bound") p_ub = plt.Rectangle((0, 1), 1, 10, fc="b") p_lb = plt.Rectangle((0, 0), 1, 1, fc="g") p_c = plt.Rectangle((0, 0), 1, 1, fc="r") p_m = plt.Rectangle((0, 0), 1, 1, fc="c") plt.legend([p_ub , p_lb, p_c, p_m ], ["Upper Bound","Lower Bound" , "Estimate","Mattched Upper Bound"],2) #l = plt.legend(bbox_to_anchor=(0, 0, 1, 1), bbox_transform=gcf().transFigure) #plt.legend([p_ub, p_lb, p_c], ["Upper Bound", "Lower Bound", "Estimate"]) global device_clock_id, local_clock_id title = "Clock Mapping from %s to %s" % (device_clock_id, local_clock_id) plt.title( title) plt.ylabel('Offset (ms)') plt.xlabel('Device Time (s)') plt.draw() mutex.release()
def testPlots(self): import matplotlib.pyplot as plt frames = list(self.it) print(len(frames)) # assert(512==list(frames)) from pprint import pprint pprint(list(self.it._consumed.items())) x = np.array([(q['start']-self.start).total_seconds() for q in frames]) def gety(name, frames=frames): return np.array([q[name] for q in frames]) a = gety('a') b = gety('b') c = gety('c') fig = plt.figure() ax = plt.axes() ax.plot(x,a, '.') ax.plot(x,b, '.') ax.plot(x,c, '.') plt.grid() plt.legend(['a1', 'a2', 'a3', 'b', 'c']) plt.title('linear time interpolation test') plt.draw() fn = '/tmp/resampler.png' fig.savefig(fn, dpi=200) print("wrote " + fn) return None
def Visualize(self,path=None,filename=None,viz_type='difference'): if path is None: path = self.result_path if filename is None: filename = '/results' im = [] if self.n<=1: fig = mpl.figure() x = np.linspace(0,1,self.m) counter = 1 for step in sorted(glob.glob(path+filename+'*.txt')): tmp = np.loadtxt(step) if viz_type=='difference': im.append(mpl.plot(x,(self.exact(x,np.zeros(self.m),counter*self.dt)-tmp),'b-')) else: im.append(mpl.plot(x,tmp,'b-')) counter += 1 ani = animation.ArtistAnimation(fig,im) mpl.show() else: X,Y = np.meshgrid(np.linspace(0,1,self.m),np.linspace(0,1,self.n)) mpl.ion() fig = mpl.figure() ax = fig.add_subplot(111,projection='3d') counter = 1 for step in sorted(glob.glob(path+filename+'*.txt')): tmp = np.loadtxt(step) wframe = ax.plot_wireframe(X,Y,(self.exact(X,Y,(counter*self.dt))-tmp)) mpl.draw() if counter==1: pass # ax.set_autoscaley_on(False) ax.collections.remove(wframe) counter +=1
def draw(ord_l, gaps): axScatter = plt.subplot(3, 1, 1) number_samples=0 # axScatter.scatter([i['seq'] for i in ord_l[-number_samples:]], [i['a'] for i in ord_l[-number_samples:]], s=2, color='r', label='ch1') axScatter.scatter([i['seq'] % 24 for i in ord_l[-number_samples:]], [i['d'] for i in ord_l[-number_samples:]], s=2, color='r', label='ch1') # axScatter.scatter(time_l[-number_samples:], b_l[-number_samples:], s=2, color='c', label='ch2') # axScatter.scatter(time_l[-number_samples:], c_l[-number_samples:], s=2, color='y', label='ch3') # axScatter.scatter(time_l[-number_samples:], d_l[-number_samples:], s=2, color='g', label='ch4') plt.ylim(-9000000, 9000000) plt.legend() axScatter.set_xlabel("Sequence Packet") axScatter.set_ylabel("Voltage") plt.title("Channels Values") # time_plot = plt.subplot(3, 1, 2) # time_plot.scatter([i['seq'] for i in ord_l[-number_samples:]], [i['delta'] for i in ord_l[-number_samples:]], s=1, color='r', label='delta') # time_plot.set_xlabel("Sequence Packet") # time_plot.set_ylabel("Delta to referencial") # ax2 = time_plot.twinx() # ax2.scatter([i['seq'] for i in ord_l[-number_samples:]], [i['ts'] for i in ord_l[-number_samples:]], s=2, color='g', label='Timestamp') # ax2.set_ylabel("Kernel time") # plt.title("Timestamp deltas") gaps_draw = plt.subplot(3, 1, 3) gaps_draw.plot([i[0] for i in gaps[-number_samples:]], [i[1] for i in gaps[-number_samples:]], color='b', marker='.', label='gaps') gaps_draw.set_ylim(-0.5, 1.5) plt.draw() # plt.savefig("res.png") plt.show()
def plot_1(x_labels, y_values, x_label, y_label, title, nb_labels): #transfom inputs to nump arrays x = np.arange(len(y_values)) y = np.array(y_values) labels = np.array(x_labels) y_max = np.amax(y) fig, ax = plt.subplots() ax.plot(x, y, 'bo-') plt.xlabel(x_label) plt.ylabel(y_label) plt.title(title) jump_step = len(y_values)/nb_labels label_indexes = np.arange(1,len(y_values),jump_step) for (X, Y, Z) in zip(x[label_indexes], y[label_indexes], labels[label_indexes]): ax.annotate('{}'.format(Z), xy=(X,Y), xytext=(X, (-0.1*y_max)), rotation=90, ha='center', size=10, textcoords='data') fig.tight_layout(pad=4) plt.draw()
def plot_np_simple(x_labels, x_values_np, y_values_np, x_label, y_label, title, nb_x_labels, style): x = np.arange(len(y_values_np)) fig, ax = plt.subplots() if style != None: ax.plot(x_values_np, y_values_np, style) else: ax.plot(x_values_np, y_values_np) plt.xlabel(x_label) plt.ylabel(y_label) plt.title(title) fontP = FontProperties() fontP.set_size('small') plt.legend(loc='lower right', prop=fontP) if x_labels != None: labels = np.array(x_labels) jump_step = len(labels)/nb_x_labels label_indexes = np.arange(1,len(labels),jump_step) for (X, Z) in zip(x[label_indexes], labels[label_indexes]): ax.annotate('{}'.format(Z), xy=(X,0), xytext=(X, (-0.1*y_max)), rotation=90, ha='center', size=10, textcoords='data') fig.tight_layout(pad=4) plt.draw()
def func(label): index = labels.index(label) lines[index].set_visible(not lines[index].get_visible()) plt.draw()
def plot_task(grid_map, grid_res, heuristic, start, goal): plot_grid(grid_map, grid_res, color='C1') # Debugger.plot_heuristic(heuristic) if heuristic else None plt.draw()
import matplotlib.pyplot as mplt import numpy as np fig = mplt.figure() ax = fig.add_subplot(111) ax.plot([1, 2, 3, 5], [1, 2, 1, 3]) plotlim = mplt.xlim() + mplt.ylim() test = np.array([[0, 0], [4, 1]]).T ax.imshow(test, cmap=mplt.cm.Greens, interpolation='bicubic', extent=plotlim) mplt.draw() mplt.show()
def toggle_visibility(label): index = labels.index(label) plot_storage.plot_list[index].set_visible(not plot_storage.plot_list[index].get_visible()) plt.draw()
def plot_data(p, x, y, result, first_pass=True, fig=None, ax=None): def select_alpha(tag): if tag in [ 'l1648f211b580m013m065m838', 'l2448f211b580m0064m0640m828', 'l3248f211b580m00235m0647m831', 0.8804 ]: alpha = 1.0 elif tag in [ 'l2464f211b600m0102m0509m635', 'l3264f211b600m00507m0507m628', 'l4864f211b600m00184m0507m628', 'l2464f211b600m00507m0507m628', 'l4064f211b600m00507m0507m628', 'l2464f211b600m0130m0509m635', 0.7036 ]: alpha = 0.7 else: alpha = 0.4 return alpha def select_color(operator): if operator in ['V']: color = '#c82506' # red elif operator in ['LR']: color = '#70b741' # green elif operator in ['LR_colormix']: color = '#0b5d12' # dark green elif operator in ['S']: color = '#51a7f9' # blue elif operator in ['S_colormix']: color = '#00397a' # dark blue return color def select_symbol(operator): if operator in ['V']: symbol = 'o' # o elif operator in ['LR']: symbol = '^' # triangle up elif operator in ['LR_colormix']: symbol = 'v' # triangle down elif operator in ['S']: symbol = 's' # square elif operator in ['S_colormix']: symbol = 'D' # diamond return symbol # unpack result fit = result['fit'] prior = result['prior'] # plot correlator data eps = [] color = [] symbol = [] alpha = [] for i in x: eps.append(fit.p['epi_%s' % i['tag']]) color.append(select_color(i['op'])) symbol.append(select_symbol(i['op'])) alpha.append(select_alpha(i['tag'])) ivdatamean = [] ivdatasdev = [] inv_w0 = 0.197327 / gv.gvar( 0.1714, 0.0015) #[GeV/fm * fm] MILC gradient flow paper abstract if first_pass: fig = plt.figure(figsize=(3.50394, 2.1655535534)) ax = plt.axes(plt_axes) # correct for FV fitoutput = np.array(result['fitc'].fit_switch(x, result['fit'].p)) result['fitc'].fv_flag = False # turn FV off nfvoutput = np.array(result['fitc'].fit_switch(x, result['fit'].p)) fvshift = fitoutput - nfvoutput for idx, mele in enumerate(y['y']): res = mele * inv_w0**4 # shift data to infinite volume if FV corrections are added if result['fitc'].ma_flag in ['reformat', 'xreformat']: res += fvshift[idx] else: res += fvshift[idx] * inv_w0**4 ivdatamean.append(res.mean) ivdatasdev.append(res.sdev) if first_pass: for i in range(len(eps)): ax.errorbar(x=eps[i].mean**2, y=ivdatamean[i], yerr=ivdatasdev[i], ls='None', marker=symbol[i], markersize=ms, elinewidth=lw, capsize=cs, mew=lw, fillstyle='none', color=color[i], mfc='black', alpha=alpha[i]) # plot finite a fit if not result['fitc'].ma_flag: xlist = [] for i in x: xlist.append(i['aw0']) xlist = np.unique(xlist) xa2 = np.linspace(0.0001**2, 0.2701**2, 271) xa = np.sqrt(xa2) fitc = fit_functions() xal = [] for o in p['op']: for a in xlist: xal = [] for i in range(len(xa)): xal.append({'op': o, 'tag': 'extrap', 'aw0': a}) post = dict() for k in prior.keys(): post[k] = fit.p[k] post['epi_extrap'] = xa if result['fitc'].ma_flag in ['reformat', 'xreformat']: r = fitc.x_reformat(xal, post)[0] else: r = fitc.unitary(xal, post)[0] * inv_w0**4 mean = np.array([i.mean for i in r]) ax.errorbar(x=xa2, y=mean, ls='--', marker='None', fillstyle='none', elinewidth=lw, color=select_color(o), alpha=select_alpha(a), lw=lw) # plot phys epsilon pi mpi_phys = 0.13957018 fpi_phys = 0.13041 / np.sqrt(2) # MeV eps_phys = mpi_phys / (4. * np.pi * fpi_phys) if first_pass: ax.axvline(eps_phys**2, ls='--', color='#a6aaa9', lw=lw) # plot continuum fit xc2 = np.linspace(0.0001**2, 0.2701**2, 271) xc = np.sqrt(xc2) xcl = [] for o in p['op']: xcl = [] for i in range(len(xc)): xcl.append({'op': o, 'tag': 'extrap', 'aw0': 0}) post = dict() for k in prior.keys(): post[k] = fit.p[k] post['epi_extrap'] = xc post[ 'mpi_extrap'] = xc * 4. * np.pi * fpi_phys # CHANGE THIS IF Fpi XPT IS ADDED fitc = fit_functions() if result['fitc'].ma_flag in ['reformat', 'xreformat']: r = fitc.x_reformat(xcl, post)[0] else: r = fitc.unitary(xcl, post)[0] * inv_w0**4 #r = fitc.unitary(xcl,post)[0]*inv_w0**4 mean = np.array([i.mean for i in r]) sdev = np.array([i.sdev for i in r]) if first_pass: ax.fill_between(xc2, mean + sdev, mean - sdev, alpha=0.2, facecolor=select_color(o)) # purple #ax.errorbar(x=xc2,y=mean,ls='-',marker='None',fillstyle='none',color='red',lw=lw) else: ax.errorbar(x=xc2, y=mean + sdev, ls='--', marker='None', fillstyle='none', color='black', lw=lw) ax.errorbar(x=xc2, y=mean - sdev, ls='--', marker='None', fillstyle='none', color='black', lw=lw) # plot formatting # for Full Plot if True: ax.set_xlim([0, xc[-1]**2]) ax.set_ylim([-0.025, 0.115]) ax.ticklabel_format(style='plain', axis='y') ax.xaxis.set_tick_params(labelsize=ts, width=lw) ax.yaxis.set_tick_params(labelsize=ts, width=lw) ax.set_xlabel('$\epsilon_\pi^2$', fontsize=fs_xy) ax.set_ylabel('$\mathcal{O}_i$~[GeV${}^4$]', fontsize=fs_xy) [i.set_linewidth(lw) for i in ax.spines.itervalues()] plt.draw() fig.savefig('./n0bb_chipt.pdf', transparent=True) #plt.show() # for V if True: ax.set_xlim([0, xc[-1]**2]) ax.set_ylim([-0.002, 0.00024]) #ax.set_yticks([-0.03, -0.02, -0.01, 0.0, 0.01]) ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax.xaxis.set_tick_params(labelsize=ts, width=lw) ax.yaxis.set_tick_params(labelsize=ts, width=lw) ax.set_xlabel('$\epsilon_\pi^2$', fontsize=fs_xy) ax.set_ylabel('$\mathcal{O}_3$~[GeV${}^4$]', fontsize=fs_xy) [i.set_linewidth(lw) for i in ax.spines.itervalues()] plt.draw() fig.savefig('./n0bbO3_chipt.pdf', transparent=True) #plt.show() return fig, ax
def plot_cv_results(train_loss, cv_loss, ind_loss=None, log_scale_p=False, plot_title='Mean Square Error Loss', filepath=None): """ Helper function to plot the results of cross-validation. You can use this when you have all three types of loss, or if you just have train and cv loss (in this case, set ind_loss to None) :param train_loss: :param cv_loss: :param ind_loss: If None, only display train_loss and cv_loss :param log_scale_p: Whether the plots are in log-scale :param plot_title: Title for the plot :param filepath: If specified, save pdf file :return: """ if ind_loss is not None: figw, figh, mydpi = 1200, 420, 96 plt.figure(figsize=(figw / mydpi, figh / mydpi), dpi=mydpi) else: figw, figh, mydpi = 800, 420, 96 plt.figure(figsize=(figw / mydpi, figh / mydpi), dpi=mydpi) # plt.figure() plt.suptitle(plot_title) if log_scale_p: ylabel = 'Log MSE Loss' else: ylabel = 'MSE Loss' x = numpy.arange(0, train_loss.shape[0]) # put y-axis on same scale for all plots if ind_loss is not None: min_ylim = min(min(train_loss), min(cv_loss), min(ind_loss)) else: min_ylim = min(min(train_loss), min(cv_loss)) min_ylim = int(numpy.floor(min_ylim)) if ind_loss is not None: max_ylim = max(max(train_loss), max(cv_loss), max(ind_loss)) else: max_ylim = max(max(train_loss), max(cv_loss)) max_ylim = int(numpy.ceil(max_ylim)) # Plot training loss if ind_loss is not None: plt.subplot(131) else: plt.subplot(121) plt.plot(x, train_loss, linewidth=2) plt.xlabel('Model Order') plt.ylabel(ylabel) plt.title('Train Loss') plt.pause(.1) # required on some systems so that rendering can happen plt.ylim(min_ylim, max_ylim) # Plot CV loss if ind_loss is not None: plt.subplot(132) else: plt.subplot(122) plt.plot(x, cv_loss, linewidth=2) plt.xlabel('Model Order') plt.ylabel(ylabel) plt.title('CV Loss') plt.pause(.1) # required on some systems so that rendering can happen plt.ylim(min_ylim, max_ylim) # Plot independent-test loss if ind_loss is not None: plt.subplot(133) plt.plot(x, ind_loss, linewidth=2) plt.xlabel('Model Order') plt.ylabel(ylabel) plt.title('Independent Test Loss') plt.pause(.1) # required on some systems so that rendering can happen plt.ylim(min_ylim, max_ylim) if ind_loss is not None: plt.subplots_adjust(right=0.95, wspace=0.4) else: plt.subplots_adjust(right=0.95, wspace=0.25, bottom=0.2) plt.draw() if filepath: plt.savefig(filepath, format='pdf')