def plot_trace(xy, ids = None, depth = 0, colormap = 'rainbow', line_color = 'k', line_width = 1, point_size = 5, title = None): """Plot trajectories with positions color coded according to discrete ids""" #if ids is not None: uids = np.unique(ids); cmap = cm.get_cmap(colormap); n = len(uids); colors = cmap(range(n), bytes = True); #lines if line_width is not None: #plt.plot(xy[:,0], xy[:,1], color = lines); plot = pg.plot(xy[:,0], xy[:,1], pen = pg.mkPen(color = line_color, width = line_width)) else: plot = pg.plot(title = title); if ids is None: sp = pg.ScatterPlotItem(pos = xy, size=point_size, pen=pg.mkPen(colors[0])); #, pxMode=True); else: sp = pg.ScatterPlotItem(size=point_size); #, pxMode=True); spots = []; for j,i in enumerate(uids): idx = ids == i; spots.append({'pos': xy[idx,:].T, 'data': 1, 'brush':pg.mkBrush(colors[j])}); #, 'size': point_size}); sp.addPoints(spots) plot.addItem(sp); return plot;
def simplePlot(): data = np.random.normal(size=1000) pg.plot(data, title="Simplest possible plotting example") data = np.random.normal(size=(500,500)) pg.image(data, title="Simplest possible image example") pg.QtGui.QApplication.exec_()
def plotAll(f): """plot all arrays in file f (code reference)""" for g in f.walkGroups(): print(g) for arr in f.listNodes(g, classname='Array'): if arr.ndim == 1 and arr.shape[0] > 1: pg.plot(arr.read())
def plotHist(self, regions = None): '''Usage: plotHist(region = None) region(int): Region to be plotted. If None, plots all regions. Plots the current ratio histograms for the regions. *** Does not need event type update. *** ''' if regions == None: # Plot all regions print "Plotting ratio histogram for all regions...\n" histPlot = pg.plot(title = "Ratio Histograms") histPlot.addLegend() histPlot.setLabel('left',"Counts") histPlot.setLabel('bottom',"Ratio") for i,hist in enumerate(self.rhist): histName = " Region " + str(i) histPlot.plot(hist, pen=(i,len(self.rhist)), name=histName) import sys if(sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() else: # Plot the region listed print "Plotting ratio histogram for region", regions, "...\n" histPlot = pg.plot(title = "Ratio Histogram") histPlot.addLegend() histPlot.setLabel('left',"Counts") histPlot.setLabel('bottom',"Ratio") for i,region in enumerate(regions): histName = " Region " + str(region) histPlot.plot(self.rhist[region,:],pen=(i,len(regions)), name=histName) import sys if(sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
def plotPower(fftData, N, C, F): v = np.absolute(np.fft.fftshift(fftData) / N) sqV = v * v p = sqV / 50.0 * 1000 * 2 # * 2 is made to take care of the fact that FFT is two-sided pdBm = np.log10(p) * 10 print "max = %f" % np.max(pdBm) print "avg = %f" % np.average(pdBm) #pg.plot(np.linspace(-Fs/2, Fs/2 - Fs / N, N), pdBm) s1 = N/2 + N * F / Fs - N * 1000000 / Fs s2 = N/2 + N * F / Fs + N * 1000000 / Fs pg.plot(pdBm[int(s1):int(s2)])
def _executeRun(self, testPlot=False): """ (private mmethod) After prepare run and initialization, this routine actually calls the run method in hoc assembles the data, saves it to disk and plots the results. Inputs: flag to put up a test plot.... """ if verbose: print('_executeRun') assert self.run_initialized == True print('Starting Vm at electrode site: {:6.2f}'.format(self.electrode_site.v)) # one way self.hf.h.t = 0 """ #while (self.hf.h.t < self.hf.h.tstop): # for i=0, tstep/dt { # self.hf.h.fadvance() # self.hf.h.run() # calls finitialize, causes offset """ self.hf.h.batch_save() # save nothing print ('Temperature in run at start: {:6.1f}'.format(self.hf.h.celsius)) self.hf.h.batch_run(self.hf.h.tstop, self.hf.h.dt, "v.dat") print('Finishing Vm: {:6.2f}'.format(self.electrode_site.v)) self.monitor['time'] = np.array(self.monitor['time']) self.monitor['time'][0] = 0. if verbose: print('post v: ', self.monitor['postsynapticV']) if testPlot: pg.plot(np.array(self.monitor['time']), np.array(self.monitor['postsynapticV'])) QtGui.QApplication.instance().exec_() # pg.mkQApp() # pl = pg.plot(np.array(self.monitor['time']), np.array(self.monitor['postsynapticV'])) # if self.filename is not None: # pl.setTitle('%s' % self.filename) # else: # pl.setTitle('executeRun, no filename') print (' Run finished') np_monitor = {} for k in self.monitor.keys(): np_monitor[k] = np.array(self.monitor[k]) np_allsecVec = OrderedDict() for k in self.allsecVec.keys(): np_allsecVec[k] = np.array(self.allsecVec[k]) self.runInfo.clist = self.clist results = Params(Sections=list(self.hf.sections.keys()), vec=np_allsecVec, monitor=np_monitor, stim=self.stim, runInfo=self.runInfo, distanceMap = self.hf.distanceMap, ) if verbose: print(' _executeRun completed') return results
def simplePlot(): data = np.random.normal(size=1000) pg.plot(data, title="Simplest possible plotting example") data = np.random.normal(size=(500,500)) pg.image(data, title="Simplest possible image example") ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'): pg.QtGui.QApplication.exec_()
def __init__(self): # start a pyqtgraph application (sigh...) self.buffer_depth = 1000 # Always start by initializing Qt (only once per application) app = QtGui.QApplication([]) # powerstack self.powerstack_init = True self.xray_power = collections.deque(maxlen = self.buffer_depth) self.plt_powerstack = pg.PlotItem(title = 'xray power vs event') self.w_powerstack = pg.ImageView(view = self.plt_powerstack) bottom = self.plt_powerstack.getAxis('bottom') bottom.setLabel('delay (fs)') left = self.plt_powerstack.getAxis('left') left.setLabel('event number ') # power vs delay self.w_xray_power = pg.plot(title = 'xray power vs delay') self.w_xray_power.setLabel('bottom', 'delay (fs)') self.w_xray_power.setLabel('left', 'power (GW)') # delay self.delay = collections.deque(maxlen = self.buffer_depth) self.event_number = collections.deque(maxlen = self.buffer_depth) self.w_delay = pg.plot(title = 'time between the two xray pulses') self.w_delay.setLabel('bottom', 'event') self.w_delay.setLabel('left', 'delay (fs)') # xtcav images self.plt_xtcav = pg.PlotItem(title = 'processed xtcav image') self.xtcav_init = True self.w_xtcav = pg.ImageView(view = self.plt_xtcav) bottom = self.plt_xtcav.getAxis('bottom') bottom.setLabel('delay (fs)') left = self.plt_xtcav.getAxis('left') left.setLabel('electron energy (MeV)') ## Start the Qt event loop signal.signal(signal.SIGINT, signal.SIG_DFL) # allow Control-C self.catch_data() sys.exit(app.exec_())
def test_CSVExporter(): plt = pg.plot() y1 = [1,3,2,3,1,6,9,8,4,2] plt.plot(y=y1, name='myPlot') y2 = [3,4,6,1,2,4,2,3,5,3,5,1,3] x2 = pg.np.linspace(0, 1.0, len(y2)) plt.plot(x=x2, y=y2) y3 = [1,5,2,3,4,6,1,2,4,2,3,5,3] x3 = pg.np.linspace(0, 1.0, len(y3)+1) plt.plot(x=x3, y=y3, stepMode=True) ex = pg.exporters.CSVExporter(plt.plotItem) ex.export(fileName='test.csv') r = csv.reader(open('test.csv', 'r')) lines = [line for line in r] header = lines.pop(0) assert header == ['myPlot_x', 'myPlot_y', 'x0001', 'y0001', 'x0002', 'y0002'] i = 0 for vals in lines: vals = list(map(str.strip, vals)) assert (i >= len(y1) and vals[0] == '') or approxeq(float(vals[0]), i) assert (i >= len(y1) and vals[1] == '') or approxeq(float(vals[1]), y1[i]) assert (i >= len(x2) and vals[2] == '') or approxeq(float(vals[2]), x2[i]) assert (i >= len(y2) and vals[3] == '') or approxeq(float(vals[3]), y2[i]) assert (i >= len(x3) and vals[4] == '') or approxeq(float(vals[4]), x3[i]) assert (i >= len(y3) and vals[5] == '') or approxeq(float(vals[5]), y3[i]) i += 1
def stream(update_interval, filter_width, max_samples): """Continuously acquires low fluid pressure sensor signal, filters it, and plots it live.""" # Plotting graph = pg.plot() graph.addLegend() signal_curve = graph.plot(pen='r', name="Raw (Noisy) Signal") filtered_curve = graph.plot(pen='b', name="Median Filtered Signal") signal_curve_updater = plotting.CurveUpdater.start(signal_curve, max_samples) filtered_curve_updater = plotting.CurveUpdater.start(filtered_curve, max_samples) signal_filter = signal.Filterer.start(filter_width=filter_width) signal_filter.proxy().register(filtered_curve_updater, 'fluid pressure') pressure_selector = signal.TupleSelector.start(0) pressure_selector.proxy().register(signal_curve_updater, 'fluid pressure') pressure_selector.proxy().register(signal_filter, 'fluid pressure') try: leg_monitor = leg.LegMonitor.start() except RuntimeError: pykka.ActorRegistry.stop_all() # stop actors in LIFO order raise leg_monitor.proxy().register(pressure_selector, 'fluid pressure') leg_monitor.tell({'command': 'start producing', 'interval': update_interval})
def plot(self, Rs=None, Vg=0): pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') # Generate plot plt = pg.plot(title=self.__class__.__name__, clear=True) plt.setYRange(0, self.IDSS_MAX) plt.setXRange(self.VP_MAX, 0) plt.showGrid(True, True, 1.0) plt.setLabel('left', "Id (mA)") plt.setLabel('bottom', "Vgs (V)") (x, y) = self.id_max_points() plt.plot(x, y, pen=pg.mkPen('g', width=3)) (x, y) = self.id_min_points() plt.plot(x, y, pen=pg.mkPen('b', width=3)) if Rs is not None: (x, y) = self.vg_intercept(Rs, Vg) plt.plot(x, y, pen=pg.mkPen('r', width=3)) # Display plot QtGui.QApplication.instance().exec_() pg.exit()
def show_fft(self): for ch in range(4): if self.chanStatus[ch] == 1: try: fa = em.fit_sine(self.timeData[ch],self.voltData[ch]) except Exception as err: print('fit_sine error:', err) fa=None if fa != None: fr = fa[1][1]*1000 # frequency in Hz dt = int(1.e6/ (20 * fr)) # dt in usecs, 20 samples per cycle try: t,v = self.p.capture1(self.sources[ch], 3000, dt) except: self.comerr() xa,ya = em.fft(v,dt) xa *= 1000 peak = self.peak_index(xa,ya) ypos = np.max(ya) pop = pg.plot(xa,ya, pen = self.traceCols[ch]) pop.showGrid(x=True, y=True) txt = pg.TextItem(text=unicode(self.tr('Fundamental frequency = %5.1f Hz')) %peak, color = 'w') txt.setPos(peak, ypos) pop.addItem(txt) pop.setWindowTitle(self.tr('Frequency Spectrum')) else: self.msg(self.tr('FFT Error'))
def estimate_kinetics(self, plot=False): kinetics_group = self.kinetics_group # Generate average decay phase avg_kinetic = kinetics_group.bsub_mean() avg_kinetic.t0 = 0 if plot: kin_plot = pg.plot(title='Kinetics') kin_plot.plot(avg_kinetic.time_values, avg_kinetic.data) else: kin_plot = None # Make initial kinetics estimate amp_est = self._psp_estimate['amp'] amp_sign = '-' if amp_est < 0 else '+' kin_fit = fit_psp(avg_kinetic, sign=amp_sign, yoffset=0, amp=amp_est, method='leastsq', fit_kws={}) if plot: kin_plot.plot(avg_kinetic.time_values, kin_fit.eval(), pen='b') rise_time = kin_fit.best_values['rise_time'] decay_tau = kin_fit.best_values['decay_tau'] latency = kin_fit.best_values['xoffset'] - 10e-3 self._psp_estimate['rise_time'] = rise_time self._psp_estimate['decay_tau'] = decay_tau self._psp_estimate['latency'] = latency return rise_time, decay_tau, latency, kin_plot
def estimate_amplitude(self, plot=False): amp_group = self.amp_group amp_est = None amp_plot = None amp_sign = None avg_amp = None n_sweeps = len(amp_group) if n_sweeps == 0: return amp_est, amp_sign, avg_amp, amp_plot, n_sweeps # Generate average first response avg_amp = amp_group.bsub_mean() if plot: amp_plot = pg.plot(title='First pulse amplitude') amp_plot.plot(avg_amp.time_values, avg_amp.data) # Make initial amplitude estimate ad = avg_amp.data dt = avg_amp.dt base = float_mode(ad[:int(10e-3/dt)]) neg = ad[int(13e-3/dt):].min() - base pos = ad[int(13e-3/dt):].max() - base amp_est = neg if abs(neg) > abs(pos) else pos if plot: amp_plot.addLine(y=base + amp_est) amp_sign = '-' if amp_est < 0 else '+' self._psp_estimate['amp'] = amp_est self._psp_estimate['amp_sign'] = amp_sign return amp_est, amp_sign, avg_amp, amp_plot, n_sweeps
def ShowGraph(self): """ app = QtGui.QApplication(sys.argv) widget = pg.PlotWidget(title="Stock Performance") widget.setWindowTitle("Graph") widget.plotItem.plot(floatStockClosePrice) """ ticker = str(self.lineEdit.text()) if self.radioButton_3.isChecked() or self.radioButton_4.isChecked() and ticker in theTickers: widget = pg.plot(floatStockClosePrice, title="Graph") ax = widget.getPlotItem().getAxis("left") ax.setLabel("Price") ax.setGrid(200) ax.showLabel() ax = widget.getPlotItem().getAxis("bottom") ax.setLabel("Year") ax.setGrid(200) ax.showLabel() widget.show() else: Tkinter.Tk().withdraw() tkMessageBox.showerror("Error: Stock Not Found", "Please try again and click 'See Projection' for graph to show.")
def draw_spectrum_analyzer(all_frames, thresh_frames): time.sleep(1) # Wait just one second pw = pg.plot(title="Spectrum Analyzer") # Window title pg.setConfigOptions(antialias=True) # Enable antialias for better resolution pw.win.resize(800, 300) # Define window size pw.win.move(540 * SCREEN_WIDTH / 1920, 500 * SCREEN_HEIGHT / 1080) # Define window position while True: # Loop over the frames of the audio / data chunks data = ''.join(all_frames[-1:]) # Get only the last frame of all frames data = numpy.fromstring(data, 'int16') # Binary string to numpy int16 data format pw.setMouseEnabled(y=False) # Disable mouse pw.setYRange(0,1000) # Set Y range of graph pw.setXRange(-(RATE/16), (RATE/16), padding=0) # Set X range of graph relative to Bit Rate pwAxis = pw.getAxis("bottom") # Get bottom axis pwAxis.setLabel("Frequency [Hz]") # Set bottom axis label f, Pxx = HearingPerception.find_frequency(data) # Call find frequency function f = f.tolist() # Numpy array to list Pxx = (numpy.absolute(Pxx)).tolist() # Numpy array to list try: # Try this block if thresh_frames[-1:][0] == EMPTY_CHUNK: # If last thresh frame is equal to EMPTY CHUNK pw.plot(x=f,y=Pxx, clear=True, pen=pg.mkPen('w', width=1.0, style=QtCore.Qt.SolidLine)) # Then plot with white pen else: # If last thresh frame is not equal to EMPTY CHUNK pw.plot(x=f,y=Pxx, clear=True, pen=pg.mkPen('y', width=1.0, style=QtCore.Qt.SolidLine)) # Then plot with yellow pen except IndexError: # If we are getting an IndexError because of this -> thresh_frames[-1:][0] pw.plot(x=f,y=Pxx, clear=True, pen=pg.mkPen('w', width=1.0, style=QtCore.Qt.SolidLine)) # Then plot with white pen pg.QtGui.QApplication.processEvents() # ??? time.sleep(0.05) # Wait a few miliseconds
def plotbar(arrY, x=None, color=None, hold=None, figureNo=None, width=0.6): global CURR, PLOTS arrY = N.asarray( arrY ) if x is not None: x = N.asarray(x) else: x = N.arange(arrY.shape[-1]) if len(arrY.shape) > 1 and arrY.shape[0] > arrY.shape[1]: arrY = N.transpose(arrY) pw = plothold(hold, figureNo) append = pw == pg if append: pw = pg.plot() kwd = {} kwd['pen'] = _pen(pw, color) kwd['brush'] = _brush(pw, color) kwd['width'] = width if len(arrY.shape) == 1: bg = pg.BarGraphItem(x=x, height=arrY, **kwd) pw.addItem(bg) else: data = [] for i in range(arr.shape[0]): bg = pg.BarGraphItem(x=x, height=arrY[i], **kwd) pw.addItem(bg) if append: PLOTS.append(pw)
def test_projection_on_lag1st(self): weights = [] # convenience wrapper for non array input -> constant function weight = core.project_on_base(self.funcs[0], self.initial_functions[1]) self.assertAlmostEqual(weight, 1.5*self.funcs[0](self.nodes[1])) # linear function -> should be fitted exactly weights.append(core.project_on_base(self.funcs[1], self.initial_functions)) self.assertTrue(np.allclose(weights[-1], self.funcs[1](self.nodes))) # quadratic function -> should be fitted somehow close weights.append(core.project_on_base(self.funcs[2], self.initial_functions)) self.assertTrue(np.allclose(weights[-1], self.funcs[2](self.nodes), atol=.5)) # trig function -> will be crappy weights.append(core.project_on_base(self.funcs[3], self.initial_functions)) if show_plots: # since test function are lagrange1st order, plotting the results is fairly easy for idx, w in enumerate(weights): pw = pg.plot(title="Weights {0}".format(idx)) pw.plot(x=self.z_values, y=self.real_values[idx+1], pen="r") pw.plot(x=self.nodes, y=w, pen="b") app.exec_()
def test_lag1st_to_trig(self): # scalar case dest_weight = core.change_projection_base(self.src_weights, self.src_test_funcs, self.trig_test_funcs[0]) dest_approx_handle_s = core.back_project_from_base(dest_weight, self.trig_test_funcs[0]) # standard case dest_weights = core.change_projection_base(self.src_weights, self.src_test_funcs, self.trig_test_funcs) dest_approx_handle = core.back_project_from_base(dest_weights, self.trig_test_funcs) error = np.sum(np.power( np.subtract(self.real_func_handle(self.z_values), dest_approx_handle(self.z_values)), 2)) if show_plots: pw = pg.plot(title="change projection base") i1 = pw.plot(x=self.z_values, y=self.real_func_handle(self.z_values), pen="r") i2 = pw.plot(x=self.z_values, y=self.src_approx_handle(self.z_values), pen=pg.mkPen("g", style=pg.QtCore.Qt.DashLine)) i3 = pw.plot(x=self.z_values, y=dest_approx_handle_s(self.z_values), pen="b") i4 = pw.plot(x=self.z_values, y=dest_approx_handle(self.z_values), pen="c") legend = pw.addLegend() legend.addItem(i1, "f(x) = x") legend.addItem(i2, "2x Lagrange1st") legend.addItem(i3, "sin(x)") legend.addItem(i4, "sin(wx) with w in [1, {0}]".format(dest_weights.shape[0])) app.exec_() # should fit pretty nice self.assertLess(error, 1e-2)
def __init__(self, ProgramStartTime = time.strftime("%Y%m%dT%H%M%S")): self.xData = collections.deque(maxlen=8640) #Capable of holding 24 hours of data recorded every 10 seconds. For plotting. self.yData = collections.deque(maxlen=8640) #After 8640, starts replacing the oldest data. self.Program_Start_Time = ProgramStartTime self.app = QtGui.QApplication([]) self.p = pg.plot() self.curve = self.p.plot(pen=pg.mkPen('b'))#pen=None, symbol='o')#pen=pg.mkPen('r')) self.initializeGraph() #Setting how the plot looks
def summary_plot_train(ind_grand_mean, plot=None, color=None, name=None): if plot is None: plot = pg.plot() plot.setLabels(left=('Vm', 'V')) plot.addLegend() plot.plot(ind_grand_mean.time_values, ind_grand_mean.data, pen=color, name=name) return plot
def start(self): self.getAttributes() if not self.parseAttributes(): print "Attribute failure." return print "zmacknut start, tvorim GA" new = GA_algorithm.GeneticAlgorithm(self.attr_dict) self.GA = new print "poustim GA" data = self.GA.start() pg.plot(data[1]) string = "Final fitness: " + str(data[1][-1]) + "\nBest fitness: " + str(data[0]) self.final_result.setText(string) QtGui.QApplication.processEvents()
def plot_entropy(self, fname): try: import numpy as np import pyqtgraph as pg import pyqtgraph.exporters as exporters except ImportError as e: return i = 0 x = [] y = [] plotted_colors = {} for r in self.results: x.append(r.offset) y.append(r.entropy) plt = pg.plot(title=fname, clear=True) # Disable auto-ranging of the Y (entropy) axis, as it # can cause some very un-intuitive graphs, particularly #for files with only high-entropy data. plt.setYRange(0, 1) if self.show_legend and has_key(self.file_markers, fname): plt.addLegend(size=(self.max_description_length*10, 0)) for (offset, description) in self.file_markers[fname]: # If this description has already been plotted at a different offset, we need to # use the same color for the marker, but set the description to None to prevent # duplicate entries in the graph legend. # # Else, get the next color and use it to mark descriptions of this type. if has_key(plotted_colors, description): color = plotted_colors[description] description = None else: color = self.COLORS[i] plotted_colors[description] = color i += 1 if i >= len(self.COLORS): i = 0 plt.plot(x=[offset,offset], y=[0,1.1], name=description, pen=pg.mkPen(color, width=2.5)) # Plot data points plt.plot(x, y, pen='y') # TODO: legend is not displayed properly when saving plots to disk if self.save_plot: exporter = exporters.ImageExporter.ImageExporter(plt.plotItem) exporter.parameters()['width'] = self.FILE_WIDTH exporter.export(binwalk.core.common.unique_file_name(fname, self.FILE_FORMAT)) else: plt.setLabel('left', self.YLABEL, units=self.YUNITS) plt.setLabel('bottom', self.XLABEL, units=self.XUNITS)
def Application(I_in, I_out, P_in, P_out, O_in, \ O_out, R_in, R_out, B_in, B_out, \ M, eMod, maxlen = 100): # start a pyqtgraph application (sigh...) import pyqtgraph as pg from PyQt4 import QtGui, QtCore import signal # Always start by initializing Qt (only once per application) app = QtGui.QApplication([]) wI = in_vs_out_widget(M*I_in[:maxlen]**0.5, I_out[:maxlen]**0.5, title = 'input / output diffraction intensities') wP = in_vs_out_widget(P_in, P_out, np.abs, 'input / output |Probe|') P_in = np.fft.fftshift(np.fft.fftn(P_in)) P_out = np.fft.fftshift(np.fft.fftn(P_out)) wPa = in_vs_out_widget(P_in, P_out, np.abs, 'input / output farfield |Probe|') wPp = in_vs_out_widget(P_in, P_out, np.angle, 'input / output farfield angle(Probe)') # check if O_out is smaller than O_in if O_out is not None and O_in is not None : if O_out.shape[0] < O_in.shape[0] : O_out.resize((O_in.shape[0], O_out.shape[1]), refcheck=False) wOa = in_vs_out_widget(O_in, O_out, np.abs, 'input / output |Object|') wOp = in_vs_out_widget(O_in, O_out, np.angle, 'input / output angle(Object)') try : wB = in_vs_out_widget(B_in, B_out, title = 'input / output background') except : pass wM = in_vs_out_widget(M, None, title = 'detector mask') eMod_plot = pg.plot(eMod, title = 'Modulus error') eMod_plot.setLabel('bottom', 'iteration') eMod_plot.setLabel('left', 'error') R_plot = pg.plot(R_in[:, 0], title = 'sample position ss, fs (red, green)', pen=pg.mkPen('r')) R_plot.plot(R_in[:, 1], pen=pg.mkPen('g')) R_plot.setLabel('bottom', 'index') R_plot.setLabel('left', 'pixels') ## Start the Qt event loop signal.signal(signal.SIGINT, signal.SIG_DFL) # allow Control-C sys.exit(app.exec_())
def main(): rospy.init_node('uwb_threshold_updater_node') # set any required ROS parameters rospy.set_param('use_sim_time', True) #----init tf listener and all Publishers------------------------------------------- # tf transform listener listener = tf.TransformListener(True, rospy.Duration(10.0)) # publisher for ground plane visualisation pub_gplane_viz = rospy.Publisher('e_gp_viz', PointCloud) # publisher for the ground plane elevation map pub_gp_emap = rospy.Publisher('gp_emap', Map) # publisher to visualise UWB FOV pub_uwb_fov = rospy.Publisher('uwb_fov', PointCloud) # publisher for ground_spectrum msg for the data fusion node pub_ground_spec = rospy.Publisher('ground_spec', GroundSpectrum) #------------------------------------------------------------------------------------ # intilise low resolution elevation map for ground plane fitting [gp_emap] = init_emap(fname=TEST1_PCD) # should set through comandline argument # interploate the elvation map gp_emap.interplotate(5) # generate gp_emap msg for data fusion node emap_msg = gen_emap_msg(gp_emap) # fit ground plane gmap = GroundMap(gp_emap) gmap.ground_fit() # instiate callback class callback_manager = CallBackClass(listener, pub_uwb_fov, gmap, pub_ground_spec) #----init subscribers -------------------------------------------------------------------- # subscriber to UWB radar scans rospy.Subscriber("radar_scan", UWBScan, callback_manager.callback_uwb) # subscriber to Traversability Map rospy.Subscriber("t_map", OccupancyGrid, callback_manager.callback_tmap) rospy.Subscriber("t_map_prop", MapProp, callback_manager.callback_tmap_prop) # subscriber to high resolution elevation[cm] map from traversability analysis node rospy.Subscriber("emap", Map, callback_manager.callback_emap) #----------------------------------------------------------------------------------------- # ground plane visualisation [gp_emin_cloud, gp_eavg_cloud, gp_emax_cloud] = gp_emap.get_pointcloud(meta_data=gmap.m_map) print "Publishing msgs" # publish pointclouds and traversability map PW = pg.plot() while not rospy.is_shutdown(): update_time_stamp(gp_emax_cloud) pub_gplane_viz.publish(gp_emax_cloud) pub_gp_emap.publish(emap_msg) # plot the learned ground spectrum assuiming completly flat terrain if len(callback_manager.intensity_avg) > 0: PW.plot(callback_manager.intensity_avg, x=callback_manager.range_bin_indexs, clear=True) PW.plot(callback_manager.intensity_max, x=callback_manager.range_bin_indexs, clear=False) pg.QtGui.QApplication.processEvents() time.sleep(5) # node shutdown procedure print "Saving learned statistics" # saves the gamma list to the current dictory # save_gamma_list(callback_manager.ground_thresh_updater.ground_spectrum.gamma_list) print "Saved Files"
def __init__(self, xName, yName): ''' xName - string - abssice name yName - string - ordinate name ''' self.pw = pg.plot() self.pw.setLabels(left=(yName)) self.pw.setLabels(bottom=(xName)) self.x = [] self.y = []
def _getview(plotview=True): if not plotview: w = pg.GraphicsWindow() w.useOpenGL(True) w.setWindowTitle('pyqtgraph example: GraphItem') v = w.addViewBox() v.setAspectLocked() else: v = pg.plot() return v
def pyqtPlot(orbitarray): print('Beginning plots...') plotwidget = pg.plot(title='Standard Map test plot') for i in range(len(orbitarray[:,0,0])): plotwidget.plot(orbitarray[i,0,:],orbitarray[i,1,:],pen=None,symbol='o',size=.01) print('plotting orbit',i,'of',len(orbitarray[:,0,0])) print('Plots are done. Now saving...') print('Plot is saved! Yay!') input() return
def trace_plot(trace, color, plot=None, x_range=None, name=None): if plot is None: plot = pg.plot() plot.setLabels(left=('Vm', 'V')) plot.setLabels(bottom=('t', 's')) if x_range is not None: plot.setXRange(x_range[0], x_range[1]) plot.plot(trace.time_values, trace.data, pen=color, name=name) app.processEvents() return plot
def __init__(self, ProgramStartTime = time.strftime("%Y%m%dT%H%M%S")): pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') self.xData = collections.deque(maxlen=8640) self.yData = collections.deque(maxlen=8640) self.Program_Start_Time = ProgramStartTime self.app = QtGui.QApplication([]) self.p = pg.plot() self.curve = self.p.plot(pen=pg.mkPen('r', width=3)) self.initializeGraph()
def newWindow(self, title): self.pw = pg.plot(title=title)
import sys from pyqtgraph.Qt import QtGui import pyqtgraph as pg from pyqtgraph.graphicsItems import TextItem # For packages that require scipy, these may be needed: # from scipy.stats import futil # from scipy.sparse.csgraph import _validation from pyqtgraph import setConfigOption pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') app = QtGui.QApplication(sys.argv) pw = pg.plot(x=[0, 1, 2, 4], y=[4, 5, 9, 6]) pw.showGrid(x=True, y=True) text = pg.TextItem( html= '<div style="text-align: center"><span style="color: #000000;"> %s</span></div>' % "here", anchor=(0.0, 0.0)) text.setPos(1.0, 5.0) pw.addItem(text) status = app.exec_() sys.exit(status)
def get_plot_data(self): c = conn.cursor() which = self.plot3_cb.currentIndex() win = pg.plot() print(which) if which == 1: query = c.execute(""" SELECT SUM(amount), type FROM finances WHERE id_user == {} GROUP BY(type) ORDER BY type ASC """.format(self.logged_id)) res = [a for a in query.fetchall()] x = np.arange(len(res)) y = np.asarray([a[0] for a in res]) if len(y) > 1: y[1] = -y[1] bg1 = pg.BarGraphItem(x=x, height=y, width=0.6, brushes='gr') win.addItem(bg1) ticks = [list(zip(range(2), ('In', 'Out')))] xax = win.getAxis('bottom') xax.setTicks(ticks) win.setTitle('Income vs expenses') elif which == 2: query = c.execute(""" SELECT SUM(amount), category FROM finances WHERE id_user == {} GROUP BY(category) ORDER BY CASE WHEN category == 'Income' THEN 1 WHEN category == 'Other income' THEN 2 WHEN category == 'Rent' THEN 3 WHEN category == 'Shopping' THEN 4 WHEN category == 'Fun' THEN 5 WHEN category == 'Other bills' THEN 6 END ASC """.format(self.logged_id)) x = np.arange(6) res = [a for a in query.fetchall()] xdict = {key: value for value, key in res} cat_list = [ 'Income', 'Other income', 'Rent', 'Shopping', 'Fun', 'Other bills' ] for item in cat_list: if item not in xdict.keys(): xdict.update({item: 0}) xdict = sorted(xdict.items(), key=lambda pair: cat_list.index(pair[0])) y = np.asarray([a[1] for a in xdict]) for i in range(0, 6): if y[i] < 0: y[i] = -y[i] bg1 = pg.BarGraphItem(x=x, height=y, width=0.6, brushes='ggrrrr') win.addItem(bg1) ticks = [ list( zip(range(6), ('Income', 'Other income', 'Rent', 'Shopping', 'Fun', 'Other bills'))) ] xax = win.getAxis('bottom') xax.setTicks(ticks) win.setTitle('Income vs expenses - by category') elif which == 3: query = c.execute(""" SELECT SUM(amount), CASE WHEN date LIKE '%-01-%' THEN 'January' WHEN date LIKE '%-02-%' THEN 'February' WHEN date LIKE '%-03-%' THEN 'March' WHEN date LIKE '%-04-%' THEN 'April' WHEN date LIKE '%-05-%' THEN 'May' WHEN date LIKE '%-06-%' THEN 'June' WHEN date LIKE '%-07-%' THEN 'July' WHEN date LIKE '%-08-%' THEN 'August' WHEN date LIKE '%-09-%' THEN 'September' WHEN date LIKE '%-10-%' THEN 'October' WHEN date LIKE '%-11-%' THEN 'November' WHEN date LIKE '%-12-%' THEN 'December' END AS dateText FROM finances WHERE id_user == {} GROUP BY dateText ORDER BY CASE WHEN date LIKE '%-01-%' THEN 1 WHEN date LIKE '%-02-%' THEN 2 WHEN date LIKE '%-03-%' THEN 3 WHEN date LIKE '%-04-%' THEN 4 WHEN date LIKE '%-05-%' THEN 5 WHEN date LIKE '%-06-%' THEN 6 WHEN date LIKE '%-07-%' THEN 7 WHEN date LIKE '%-08-%' THEN 8 WHEN date LIKE '%-09-%' THEN 9 WHEN date LIKE '%-10-%' THEN 10 WHEN date LIKE '%-11-%' THEN 11 WHEN date LIKE '%-12-%' THEN 12 END ASC """.format(self.logged_id)) x = np.arange(12) res = [a for a in query.fetchall()] xdict = {key: value for value, key in res} cat_list = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] for item in cat_list: if item not in xdict.keys(): xdict.update({item: 0}) xdict = sorted(xdict.items(), key=lambda pair: cat_list.index(pair[0])) y = np.asarray([a[1] for a in xdict]) bg1 = pg.BarGraphItem(x=x, height=y, width=0.5, brush='b') win.addItem(bg1) ticks = [ list( zip(range(12), ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'))) ] xax = win.getAxis('bottom') xax.setTicks(ticks) win.setTitle('Income vs expenses - by month')
# -*- coding: utf-8 -*- """ Created on Thu Feb 7 23:11:49 2019 @author: justRandom """ import pyqtgraph as pg rand = [] for i in range(100): rand.append(i) pg.plot(rand)
WSPlot = [] VolFlowPlot = [] VolPlot = [] TempPlot = [] TimePlot = [] # Read all the ADC channel values in a list. readValues = [0] * 4 print("Integration V2") ### --> SETUP END ### LOOP WindSpeedPlot = pg.plot() VolumePlot = pg.plot() while True: # Get values from sensor VolRead, VolFlowRead, WSRead, TempRead, dtRead = getValues() # Append to plot lists dtPlot.append(dtRead) TempPlot.append(TempRead) VolFlowPlot.append(VolFlowRead) VolPlot.append(VolRead) WSPlot.append(WSRead) # Sums of dt is time TimePlot.append(sum(dtPlot)) # Plot
def plotmaps_pg(self, mode = 0, target = 1, gfilter = 0): pos = np.array([0.0, 0.33, 0.67, 1.0]) color = np.array([[0,0,0,255], [255,128,0,255], [255,255,0,255],[0,0,0,255]], dtype=np.ubyte) maps = pg.ColorMap(pos, color) lut = maps.getLookupTable(0.0, 1.0, 256) # # ## Set up plots/images in window # self.view = pg.GraphicsView() # l = pg.GraphicsLayout(border=(100,100,100)) # self.view.setCentralItem(l) # self.amp1View = l.addViewBox(lockAspect=True) # self.amp2View = l.addViewBox(lockAspect=True) # self.waveformPlot = l.addPlot(title="Waveforms") # l.nextRow() # self.phase1View = l.addViewBox(lockAspect=True) # self.phase2View = l.addViewBox(lockAspect=True) # self.fftPlot = l.addPlot(title="FFTs") # self.phiView = l.addViewBox(lockAspect=True) global D max1 = numpy.amax(self.amplitudeImage1) if target > 1: max1 = numpy.amax([max1, numpy.amax(self.amplitudeImage2)]) max1 = 10.0*int(max1/10.0) # pylab.figure(1) # pylab.subplot(2,3,1) # pylab.title('Amplitude Map1') # #scipy.ndimage.gaussian_filter(self.amplitudeImage1, 2, order=0, output=self.amplitudeImage1, mode='reflect') ampimg = scipy.ndimage.gaussian_filter(self.amplitudeImage1,gfilt, order=0, mode='reflect') #self.amp1View.addItem(pg.ImageItem(ampimg)) self.amp1 = pg.image(ampimg, title="Amplitude Map 1", levels=(0.0, max1)) #imga1 = pylab.imshow(ampimg) #pylab.colorbar() #imga1.set_clim = (0.0, max1) #pylab.subplot(2,3,4) #pylab.title('Phase Map1') phsmap=scipy.ndimage.gaussian_filter(self.phaseImage1, gfilt, order=0,mode='reflect') #self.phase1View.addItem(pg.ImageItem(phsmap)) self.phs1 = pg.image(phsmap, title='Phase Map 1') #self.phs1.getHistogramWidget().item.gradient. #imgp1 = pylab.imshow(phsmap, cmap=matplotlib.cm.hsv) #pylab.colorbar() print "plotmaps Block 1" print "mode:", mode self.wavePlt = pg.plot(title='Waveforms') if mode == 0 or mode == 2: self.fftPlt = pg.plot(title = 'FFTs') if mode == 0: #pylab.subplot(2,3,3) # for i in range(0, self.nPhases): # self.wavePlt.plot(ta.n_times, D[:,5,5].view(ndarray)) # #pylab.plot(ta.n_times, D[:,5,5].view(ndarray)) # #pylab.plot(self.n_times, D[:,i*55+20, 60]) # #pylab.hold('on') # #pylab.title('Waveforms') #pylab.subplot(2,3,6) for i in range(0, self.nPhases): self.fftPlt.plot(ta.n_times, self.DF[:,5,5].view(ndarray)) #pylab.plot(ta.n_times, self.DF[:,5,5].view(ndarray)) #pylab.plot(self.DF[:,i*55+20, 60]) #pylab.hold('on') #pylab.title('FFTs') print "plotmaps Block 2" if mode == 1 and target > 1: #pylab.subplot(2,3,2) #pylab.title('Amplitude Map2') #scipy.ndimage.gaussian_filter(self.amplitudeImage2, 2, order=0, output=self.amplitudeImage2, mode='reflect') ampImg2 = scipy.ndimage.gaussian_filter(self.amplitudeImage2,gfilt, order=0, mode='reflect') #imga2 = pylab.imshow(ampImg2) #self.amp2View.addItem(pg.ImageItem(ampImg2)) self.amp2 = pg.image(ampImg2, title='Amplitude Map 2', levels=(0.0, max1)) #imga2.set_clim = (0.0, max1) #pylab.colorbar() #pylab.subplot(2,3,5) phaseImg2 = scipy.ndimage.gaussian_filter(self.phaseImage2, gfilt, order=0,mode='reflect') #self.phase2View.addItem(pg.ImageItem(phaseImg2)) self.phs2 = pg.image(phaseImg2, title="Phase Map 2", levels=(-np.pi/2.0, np.pi/2.0)) #imgp2 = pylab.imshow(phaseImg2, cmap=matplotlib.cm.hsv) #pylab.colorbar() #imgp2.set_clim=(-numpy.pi/2.0, numpy.pi/2.0) #pylab.title('Phase Map2') ### doubled phase map #pylab.subplot(2,3,6) #scipy.ndimage.gaussian_filter(self.phaseImage2, 2, order=0, output=self.phaseImage2, mode='reflect') np1 = scipy.ndimage.gaussian_filter(self.phaseImage1, gfilt, order=0, mode='reflect') np2 = scipy.ndimage.gaussian_filter(self.phaseImage2, gfilt, order=0, mode='reflect') dphase = (np1 + np2)/2 print 'shape of dphase', dphase.shape #dphase = self.phaseImage1 - self.phaseImage2 print 'min phase', np.amin(dphase) print 'max phase', np.amax(dphase) # for i in range(dphase.shape[0]): # for j in range(dphase.shape[1]): # #for k in range(dphase.shape[2]): # if dphase[i,j]<0: # dphase[i,j] = dphase[i,j]+2*np.pi print 'min phase', np.amin(dphase) print 'max phase', np.amax(dphase) self.win = pg.GraphicsWindow() view = self.win.addViewBox() view.setAspectLocked(True) item = pg.ImageItem(dphase) view.addItem(item) item.setLookupTable(lut) item.setLevels([-np.pi,np.pi]) # self.colorlevels = pg.GradientEditorItem() # self.colorlevels.getLookupTable(17) # self.colorlevels.setColorMode('rgb') # self.colorlevels.setOrientation('right') # self.colorlevels.setPos(-10,0) # view.addItem(self.colorlevels) gradlegend = pg.GradientLegend((10,100),(0,0)) #gradlegend.setIntColorScale(0,255) #gradlegend.setGradient(self.creategradient()) gradlegend.setGradient(maps.getGradient()) view.addItem(gradlegend) #self.phiView.addItem(pg.ImageItem(dphase)) self.phi = pg.image(dphase, title="2x Phi map", levels=(-np.pi, np.pi)) #imgpdouble = pylab.imshow(dphase, cmap=matplotlib.cm.hsv) #pylab.title('2x Phi map') #pylab.colorbar() #imgpdouble.set_clim=(-numpy.pi, numpy.pi) print "plotmaps Block 3" # if mode == 2 or mode == 1: # # if self.phasex == []: # # self.phasex = numpy.random.randint(0, high=D.shape[1], size=D.shape[1]) # # self.phasey = numpy.random.randint(0, high=D.shape[2], size=D.shape[2]) # #pylab.subplot(2,3,3) # sh = D.shape # spr = sh[2]/self.nPhases # wvfms=[] # for i in range(0, self.nPhases): # Dm = self.avgimg[i*spr,i*spr] # diagonal run # wvfms=self.n_times, 100.0*(D[:,self.phasex[i], self.phasey[i]]/Dm) # #pylab.plot(self.n_times, 100.0*(D[:,self.phasex[i], self.phasey[i]]/Dm)) # self.wavePlt.plot(self.n_times, 100.0*(D[:,self.phasex[i], self.phasey[i]]/Dm)) # #pylab.hold('on') # self.plotlist.append(pg.image(wvfms, title="Waveforms")) # print "it worked" # pylab.title('Waveforms') # print "plotmaps Block 4" if mode == 2: #pylab.subplot(2,3,6) for i in range(0, self.nPhases): #pylab.plot(self.DF[1:,80, 80]) spectrum = np.abs(self.DF)**2 self.fftPlt.plot(spectrum[1:,80,80]) #pyqtgraph.intColor(index, hues=17, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255, **kargs) #self.fftPlt.plot(self.DF[1:,80,80]) ## causing errors and i'm not sure what the desired thing is, Exception: Can not plot complex data types. #pass #pylab.hold('on') # self.plotlist.append(pg.image(wvfms, title="Waveforms")) print "waveform plotting worked" # pylab.title('Waveforms') print "plotmaps Block 4" # if mode == 2: # #pylab.subplot(2,3,6) # for i in range(0, self.nPhases): # #pylab.plot(self.DF[1:,80, 80]) # spectrum = np.abs(self.DF)**2 # self.fftPlt.plot(spectrum[1:,80,80]) # #pyqtgraph.intColor(index, hues=17, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255, **kargs) # #self.fftPlt.plot(self.DF[1:,80,80]) ## causing errors and i'm not sure what the desired thing is, Exception: Can not plot complex data types. # #pass # #pylab.hold('on') # #pylab.title('FFTs') # print "plotmaps Block 5" # print "plotting complete" return
args = parser.parse_args(sys.argv[1:]) species = {'mouse': ['o', (0, 0, 255, 150)], 'human': ['s', (0, 255, 0, 150)]} metrics = ['area_400_10000bp', 'picogreen_yield','norm_marker_sum', 'genes_detected', 'tree_call'] q = db.query(db.PatchSeq, db.Experiment.acq_timestamp) q = q.join(db.Cell, db.PatchSeq.cell_id==db.Cell.id) q = q.join(db.Experiment, db.Cell.experiment_id==db.Experiment.id) q = q.join(db.Slice, db.Experiment.slice_id==db.Slice.id) q = q.filter(db.Experiment.operator_name=='Operator Z') for metric in metrics: ticks = None if args.timeline: time_plt = pg.plot() time_plt.addLegend() if args.hist: hist_plt = pg.plot() hist_plt.addLegend() for organism, symbols in species.items(): patchseq_cells = q.filter(db.Slice.species==organism) symbol = symbols[0] color = symbols[1] values = [getattr(c[0], metric) for c in patchseq_cells if getattr(c[0], metric) is not None] if metric == 'tree_call': tree_map = {'Core': 4, 'I1': 3, 'I2': 2, 'I3': 1, 'PoorQ': 0} values = [tree_map[v] + random.uniform(-0.3, 0.3) for v in values] ticks = [[(tick_val, tick_name) for tick_name, tick_val in tree_map.items()]] if args.timeline and len(values) > 0:
def make_Graphs(self): """Method to initialize the different plots. Creates a plot with grid and legend, then adds it to the coresponding layout. """ self.tempplt = pg.plot() self.tempplt.setYRange(-1, 100) self.tempplt.showGrid(x=True, y=True) self.tempplt.addLegend() for i in range(0, 10): self.tempplt.plot(np.zeros(10), np.zeros(10), pen=self.colorlist[i], name=self.motornames[i]) self.tempplt.addLegend(offset=79) #creates a legend by plotting a single point for each motor, just so they show up in the legend. #Apparently you are supposed to do it that way... for i in range(10, 20): self.tempplt.plot(np.zeros(10), np.zeros(10), pen=self.colorlist[i], name=self.motornames[i]) self.layout_temp = QtGui.QHBoxLayout() self.combobox3 = QComboBox() self.combobox3.addItem('All') for i in self.motornames: self.combobox3.addItem(i) self._widget.Temperatur.setLayout(self.layout_temp) self.layout_temp.addWidget(self.tempplt) self.layout_temp.addWidget(self.combobox3) self.tempplt.win.hide() self.torqueplt = pg.plot() self.torqueplt.setYRange(-1, 2) self.torqueplt.showGrid(x=True, y=True) self.torqueplt.addLegend() for i in range(0, 10): self.torqueplt.plot(np.zeros(10), np.zeros(10), pen=self.colorlist[i], name=self.motornames[i]) self.torqueplt.addLegend(offset=79) for i in range(10, 20): self.torqueplt.plot(np.zeros(10), np.zeros(10), pen=self.colorlist[i], name=self.motornames[i]) self.layout_torque = QtGui.QHBoxLayout() self._widget.Torque.setLayout(self.layout_torque) self.layout_torque.addWidget(self.torqueplt) self.combobox = QComboBox() self.combobox.addItem('All') for i in self.motornames: self.combobox.addItem(i) self.layout_torque.addWidget(self.combobox) self.torqueplt.win.hide() self.voltageplt = pg.plot() self.voltageplt.setYRange(-1, 30) self.voltageplt.showGrid(x=True, y=True) self.voltageplt.addLegend() for i in range(0, 10): self.voltageplt.plot(np.zeros(10), np.zeros(10), pen=self.colorlist[i], name=self.motornames[i]) self.voltageplt.addLegend(offset=79) for i in range(10, 20): self.voltageplt.plot(np.zeros(10), np.zeros(10), pen=self.colorlist[i], name=self.motornames[i]) self.layout_voltage = QtGui.QHBoxLayout() self.combobox2 = QComboBox() self.combobox2.addItem('All') for i in self.motornames: self.combobox2.addItem(i) self._widget.Voltage.setLayout(self.layout_voltage) self.layout_voltage.addWidget(self.voltageplt) self.layout_voltage.addWidget(self.combobox2) self.voltageplt.win.hide()
return QtCore.QRectF(self.picture.boundingRect()) app = QtGui.QApplication([]) data = [ ## fields are (time, open, close, min, max). [1., 10, 13, 5, 15], [2., 13, 17, 9, 20], [3., 17, 14, 11, 23], [4., 14, 15, 5, 19], [5., 15, 9, 8, 22], [6., 9, 15, 8, 16], ] item = CandlestickItem() item.set_data(data) plt = pg.plot() plt.addItem(item) plt.setWindowTitle('pyqtgraph example: customGraphicsItem') def update(): global item, data data_len = len(data) rand = random.randint(0, len(data)-1) new_bar = data[rand][:] new_bar[0] = data_len data.append(new_bar) item.set_data(data) app.processEvents() ## force complete redraw for every plot timer = QtCore.QTimer()
sign='+' threshold = [None] qc_params = (sign, [1e-3]) holding = [-55, -75] freqs = [10, 20, 50, 100] rec_t = [250, 500, 1000, 2000, 4000] sweep_threshold = 3 deconv = True # cache_file = 'train_response_cache.pkl' # response_cache = load_cache(cache_file) # cache_change = [] # log_rec_plt = pg.plot() # log_rec_plt.setLogMode(x=True) qc_plot = pg.plot() ind_plot = PlotGrid() ind_plot.set_shape(4, len(connection_types)) ind_plot.show() rec_plot = PlotGrid() rec_plot.set_shape(5, len(connection_types)) rec_plot.show() if deconv is True: deconv_ind_plot = PlotGrid() deconv_ind_plot.set_shape(4, len(connection_types)) deconv_ind_plot.show() deconv_rec_plot = PlotGrid() deconv_rec_plot.set_shape(5,len(connection_types)) deconv_rec_plot.show() summary_plot = PlotGrid() summary_plot.set_shape(len(connection_types), 2)
#_pgimage = pg.image(title='Current Image {}'.format(xfel.__version__)) def plotimage(d): ''' Plots current time of flight data from one shot. Updates _tofplot window Input: image data Output: None, updates plot window ''' _pgimage.setImage(d, autoRange=False) pg.QtGui.QApplication.processEvents() _pgimage2 = pg.image(title='AverageImage {}'.format(xfel.__version__)) _pghistplot = pg.plot(title='HistBrightness {}'.format(xfel.__version__)) _pgbrightestimg = pg.image(title='Brightest Shots {}'.format(xfel.__version__)) brightestlen = 15 imagehist = xfel.DataBuffer(brightestlen) tidhist = xfel.DataBuffer(brightestlen) brightnesshist = xfel.DataBuffer(1000) _brightlasttid = -1 def plotbrightest(d, tid=0): ''' Plots current time of flight data from one shot. Updates _tofplot window Input: image data Output:
#!/usr/bin/python3 import sys import pyqtgraph as pg pg.setConfigOption('antialias', True) if len(sys.argv) < 2 or sys.argv[1] == '-': f = sys.stdin else: f = open(sys.argv[1], 'r') lines = iter(f) next(lines) pairs = map(lambda line: map(int, line.split(',')), lines) xvals, yvals = zip(*pairs) f.close() pg.plot(xvals, yvals, symbol='o') pg.QtGui.QApplication.exec_()
from scipy import signal fs = 250 sec_to_plot = 10 n_samples = sec_to_plot * fs n_channels = 32 x = np.linspace(0, sec_to_plot, n_samples) y = np.zeros(shape=(n_channels, n_samples)) * np.nan data = np.random.normal(size=(n_channels, 100000)) * 10 b, a = signal.butter(2, 10 / fs * 2) data = signal.lfilter(b, a, data, axis=1) a = QtGui.QApplication([]) plotWidget = pg.plot() plotWidget.getPlotItem().hideAxis('left') plotWidget.getPlotItem().setMenuEnabled(enableMenu=False) plotWidget.getPlotItem().setMouseEnabled(x=False, y=False) curves = [] for i in range(n_channels): c = pg.PlotDataItem(pen=(i, n_channels * 1.3), name='sf') plotWidget.addItem(c) c.setPos(0, i + 1) curves.append(c) vertical_line = pg.PlotDataItem(name='sf') plotWidget.addItem(vertical_line)
shape = jsonWave["dimension"]["size"] raw = np.array(jsonWave["data"]["raw"], dtype=dtype) return raw.reshape(shape, order="F") if __name__ == '__main__': import sys if len(sys.argv) < 3: path = 'root:MIES:ITCDevices:ITC1600:Device0' file = 'OscilloscopeData' else: path, file = sys.argv[1:3] import pyqtgraph as pg app = pg.mkQApp() plt = pg.plot(labels={'bottom': ('Time', 's')}) igor = IgorThread() fut = [] def update(): global data, scaling, fut if not plt.isVisible(): timer.stop() return if len(fut) < 10: fut.append(igor.getWave(path, file)) if fut[0].done(): data, scaling = fut.pop(0).result() #data, scaling = igor.getWave('root:MIES:ITCDevices:ITC1600:Device0:TestPulse', 'TestPulseITC')
def save_fit_psp_test_set(): """NOTE THIS CODE DOES NOT WORK BUT IS HERE FOR DOCUMENTATION PURPOSES SO THAT WE CAN TRACE BACK HOW THE TEST DATA WAS CREATED IF NEEDED. Create a test set of data for testing the fit_psp function. Uses Steph's original first_puls_feature.py code to filter out error causing data. Example run statement python save save_fit_psp_test_set.py --organism mouse --connection ee Comment in the code that does the saving at the bottom """ import pyqtgraph as pg import numpy as np import csv import sys import argparse from multipatch_analysis.experiment_list import cached_experiments from manuscript_figures import get_response, get_amplitude, response_filter, feature_anova, write_cache, trace_plot, \ colors_human, colors_mouse, fail_rate, pulse_qc, feature_kw from synapse_comparison import load_cache, summary_plot_pulse from neuroanalysis.data import TSeriesList, TSeries from neuroanalysis.ui.plot_grid import PlotGrid from multipatch_analysis.connection_detection import fit_psp from rep_connections import ee_connections, human_connections, no_include, all_connections, ie_connections, ii_connections, ei_connections from multipatch_analysis.synaptic_dynamics import DynamicsAnalyzer from scipy import stats import time import pandas as pd import json import os app = pg.mkQApp() pg.dbg() pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') parser = argparse.ArgumentParser( description= 'Enter organism and type of connection you"d like to analyze ex: mouse ee (all mouse excitatory-' 'excitatory). Alternatively enter a cre-type connection ex: sim1-sim1') parser.add_argument('--organism', dest='organism', help='Select mouse or human') parser.add_argument('--connection', dest='connection', help='Specify connections to analyze') args = vars(parser.parse_args(sys.argv[1:])) all_expts = cached_experiments() manifest = { 'Type': [], 'Connection': [], 'amp': [], 'latency': [], 'rise': [], 'rise2080': [], 'rise1090': [], 'rise1080': [], 'decay': [], 'nrmse': [], 'CV': [] } fit_qc = {'nrmse': 8, 'decay': 499e-3} if args['organism'] == 'mouse': color_palette = colors_mouse calcium = 'high' age = '40-60' sweep_threshold = 3 threshold = 0.03e-3 connection = args['connection'] if connection == 'ee': connection_types = ee_connections.keys() elif connection == 'ii': connection_types = ii_connections.keys() elif connection == 'ei': connection_types = ei_connections.keys() elif connection == 'ie': connection_types == ie_connections.keys() elif connection == 'all': connection_types = all_connections.keys() elif len(connection.split('-')) == 2: c_type = connection.split('-') if c_type[0] == '2/3': pre_type = ('2/3', 'unknown') else: pre_type = (None, c_type[0]) if c_type[1] == '2/3': post_type = ('2/3', 'unknown') else: post_type = (None, c_type[0]) connection_types = [(pre_type, post_type)] elif args['organism'] == 'human': color_palette = colors_human calcium = None age = None sweep_threshold = 5 threshold = None connection = args['connection'] if connection == 'ee': connection_types = human_connections.keys() else: c_type = connection.split('-') connection_types = [((c_type[0], 'unknown'), (c_type[1], 'unknown'))] plt = pg.plot() scale_offset = (-20, -20) scale_anchor = (0.4, 1) holding = [-65, -75] qc_plot = pg.plot() grand_response = {} expt_ids = {} feature_plot = None feature2_plot = PlotGrid() feature2_plot.set_shape(5, 1) feature2_plot.show() feature3_plot = PlotGrid() feature3_plot.set_shape(1, 3) feature3_plot.show() amp_plot = pg.plot() synapse_plot = PlotGrid() synapse_plot.set_shape(len(connection_types), 1) synapse_plot.show() for c in range(len(connection_types)): cre_type = (connection_types[c][0][1], connection_types[c][1][1]) target_layer = (connection_types[c][0][0], connection_types[c][1][0]) conn_type = connection_types[c] expt_list = all_expts.select(cre_type=cre_type, target_layer=target_layer, calcium=calcium, age=age) color = color_palette[c] grand_response[conn_type[0]] = { 'trace': [], 'amp': [], 'latency': [], 'rise': [], 'dist': [], 'decay': [], 'CV': [], 'amp_measured': [] } expt_ids[conn_type[0]] = [] synapse_plot[c, 0].addLegend() for expt in expt_list: for pre, post in expt.connections: if [expt.uid, pre, post] in no_include: continue cre_check = expt.cells[pre].cre_type == cre_type[ 0] and expt.cells[post].cre_type == cre_type[1] layer_check = expt.cells[pre].target_layer == target_layer[ 0] and expt.cells[post].target_layer == target_layer[1] if cre_check is True and layer_check is True: pulse_response, artifact = get_response( expt, pre, post, analysis_type='pulse') if threshold is not None and artifact > threshold: continue response_subset, hold = response_filter( pulse_response, freq_range=[0, 50], holding_range=holding, pulse=True) if len(response_subset) >= sweep_threshold: qc_plot.clear() qc_list = pulse_qc(response_subset, baseline=1.5, pulse=None, plot=qc_plot) if len(qc_list) >= sweep_threshold: avg_trace, avg_amp, amp_sign, peak_t = get_amplitude( qc_list) # if amp_sign is '-': # continue # #print ('%s, %0.0f' %((expt.uid, pre, post), hold, )) # all_amps = fail_rate(response_subset, '+', peak_t) # cv = np.std(all_amps)/np.mean(all_amps) # # # weight parts of the trace during fitting dt = avg_trace.dt weight = np.ones( len(avg_trace.data )) * 10. #set everything to ten initially weight[int(10e-3 / dt):int( 12e-3 / dt)] = 0. #area around stim artifact weight[int(12e-3 / dt):int( 19e-3 / dt)] = 30. #area around steep PSP rise # check if the test data dir is there and if not create it test_data_dir = 'test_psp_fit' if not os.path.isdir(test_data_dir): os.mkdir(test_data_dir) save_dict = {} save_dict['input'] = { 'data': avg_trace.data.tolist(), 'dtype': str(avg_trace.data.dtype), 'dt': float(avg_trace.dt), 'amp_sign': amp_sign, 'yoffset': 0, 'xoffset': 14e-3, 'avg_amp': float(avg_amp), 'method': 'leastsq', 'stacked': False, 'rise_time_mult_factor': 10., 'weight': weight.tolist() } # need to remake trace because different output is created avg_trace_simple = TSeries( data=np.array(save_dict['input']['data']), dt=save_dict['input'] ['dt']) # create TSeries object psp_fits_original = fit_psp( avg_trace, sign=save_dict['input']['amp_sign'], yoffset=save_dict['input']['yoffset'], xoffset=save_dict['input']['xoffset'], amp=save_dict['input']['avg_amp'], method=save_dict['input']['method'], stacked=save_dict['input']['stacked'], rise_time_mult_factor=save_dict['input'] ['rise_time_mult_factor'], fit_kws={ 'weights': save_dict['input']['weight'] }) psp_fits_simple = fit_psp( avg_trace_simple, sign=save_dict['input']['amp_sign'], yoffset=save_dict['input']['yoffset'], xoffset=save_dict['input']['xoffset'], amp=save_dict['input']['avg_amp'], method=save_dict['input']['method'], stacked=save_dict['input']['stacked'], rise_time_mult_factor=save_dict['input'] ['rise_time_mult_factor'], fit_kws={ 'weights': save_dict['input']['weight'] }) print expt.uid, pre, post if psp_fits_original.nrmse( ) != psp_fits_simple.nrmse(): print ' the nrmse values dont match' print '\toriginal', psp_fits_original.nrmse() print '\tsimple', psp_fits_simple.nrmse()
import pyqtgraph as pg import numpy as np x = np.random.normal(size=1000) y = np.random.normal(size=1000) graph = pg.plot(x, y, pen=None, symbol='o') ## setting pen=None disables line drawing
def first_pulse_plot(expt_list, name=None, summary_plot=None, color=None, scatter=0, features=False): amp_plots = pg.plot() amp_plots.setLabels(left=('Vm', 'V')) amp_base_subtract = [] avg_amps = {'amp': [], 'latency': [], 'rise': []} for expt in expt_list: for pre, post in expt.connections: if expt.cells[pre].cre_type == cre_type[0] and expt.cells[post].cre_type == cre_type[1]: avg_amp, avg_trace, n_sweeps = responses(expt, pre, post, thresh=0.03e-3, filter=[[0, 50], [-68, -72]]) if expt.cells[pre].cre_type in EXCITATORY_CRE_TYPES and avg_amp < 0: continue elif expt.cells[pre].cre_type in INHIBITORY_CRE_TYPES and avg_amp > 0: continue if n_sweeps >= 10: avg_trace.t0 = 0 avg_amps['amp'].append(avg_amp) base = float_mode(avg_trace.data[:int(10e-3 / avg_trace.dt)]) amp_base_subtract.append(avg_trace.copy(data=avg_trace.data - base)) if features is True: if avg_amp > 0: amp_sign = '+' else: amp_sign = '-' psp_fits = fit_psp(avg_trace, sign=amp_sign, yoffset=0, amp=avg_amp, method='leastsq', fit_kws={}) avg_amps['latency'].append(psp_fits.best_values['xoffset'] - 10e-3) avg_amps['rise'].append(psp_fits.best_values['rise_time']) current_connection_HS = post, pre if len(expt.connections) > 1 and args.recip is True: for i,x in enumerate(expt.connections): if x == current_connection_HS: # determine if a reciprocal connection amp_plots.plot(avg_trace.time_values, avg_trace.data - base, pen={'color': 'r', 'width': 1}) break elif x != current_connection_HS and i == len(expt.connections) - 1: # reciprocal connection was not found amp_plots.plot(avg_trace.time_values, avg_trace.data - base) else: amp_plots.plot(avg_trace.time_values, avg_trace.data - base) app.processEvents() if len(amp_base_subtract) != 0: print(name + ' n = %d' % len(amp_base_subtract)) grand_mean = TraceList(amp_base_subtract).mean() grand_amp = np.mean(np.array(avg_amps['amp'])) grand_amp_sem = stats.sem(np.array(avg_amps['amp'])) amp_plots.addLegend() amp_plots.plot(grand_mean.time_values, grand_mean.data, pen={'color': 'g', 'width': 3}, name=name) amp_plots.addLine(y=grand_amp, pen={'color': 'g'}) if grand_mean is not None: print(legend + ' Grand mean amplitude = %f +- %f' % (grand_amp, grand_amp_sem)) if features is True: feature_list = (avg_amps['amp'], avg_amps['latency'], avg_amps['rise']) labels = (['Vm', 'V'], ['t', 's'], ['t', 's']) titles = ('Amplitude', 'Latency', 'Rise time') else: feature_list = [avg_amps['amp']] labels = (['Vm', 'V']) titles = 'Amplitude' summary_plots = summary_plot_pulse(feature_list[0], labels=labels, titles=titles, i=scatter, grand_trace=grand_mean, plot=summary_plot, color=color, name=legend) return avg_amps, summary_plots else: print ("No Traces") return None, avg_amps, None, None
#!/usr/bin/python # -*- coding: utf-8 -*- """ Test the speed of rapidly updating multiple plot curves """ ## Add path to library (just for examples; you do not need this) import initExample from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg from pyqtgraph.ptime import time app = pg.mkQApp("MultiPlot Speed Test") plot = pg.plot() plot.setWindowTitle('pyqtgraph example: MultiPlotSpeedTest') plot.setLabel('bottom', 'Index', units='B') nPlots = 100 nSamples = 500 curves = [] for idx in range(nPlots): curve = pg.PlotCurveItem(pen=(idx, nPlots * 1.3)) plot.addItem(curve) curve.setPos(0, idx * 6) curves.append(curve) plot.setYRange(0, nPlots * 6) plot.setXRange(0, nSamples) plot.resize(600, 900)
##import sys ##from PyQt5.QtWidgets import QMainWindow, QApplication ##from PyQt5 import QtCore ##from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import numpy as np ##app = QtGui.QApplication([]) data = np.array([[0, 1], [1, 1]], ndmin=2) print(data) pg.plot(data) ''' win = pg.GraphicsWindow(title="Basic plotting examples") win.resize(1000,600) win.setWindowTitle('pyqtgraph example: Plotting') k = 0 win = pg.GraphicsWindow() #win.plot(data) # data can be a list of values or a numpy array '''
""" import numpy as np import pyqtgraph as pg print("Qt Version: {}".format(pg.QtCore.QT_VERSION_STR)) print("PyQt Version: {}".format(pg.QtCore.PYQT_VERSION_STR)) data = np.random.normal(size=20) data2 = np.random.normal(size=20) data2 = data2.astype(np.float32) print("data2.dtype: {}".format(data2.dtype)) #data2[0] = np.nan data2[10] = 1e14 # Works data2[10] = 4.17e14 # still works # data2[10] = 4.18e14 # Fails #data2[10] = 2e27 data2[15] = np.nan #data2[100] = 4.5e14 # See pyqtgraph issue #1011 #pg.plot(data, title="no NaN") pg.plot(data2, title="one NaN") pg.QtGui.QApplication.exec_()
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg from pyqtgraph.ptime import time import serial app = QtGui.QApplication([]) pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'b') p = pg.plot(pen='r') p.setWindowTitle('live plot from serial') curve = p.plot(pen='r') data = [0] raw = serial.Serial("/dev/ttyUSB0", 115200) # raw.open() try: thres = int(sys.argv[1]) except (ValueError, TypeError, IndexError): thres = 10000 print "Parameter missing or not valid for plot Y-axis limits (default=10000)" def update(): global curve, data
BAUD_RATE = 115200 if __name__ == '__main__': # automatically find Stellaris ICDI port icdi = list(list_ports.grep('USB0')) if(not icdi): print('No ICDI port found! Please make sure' \ ' you plugged in the board!') sys.exit(1) port = Serial(icdi[0][0], BAUD_RATE, timeout=5) # prepare real time plot pw = pg.plot(title="Active Channels") pw.setXRange(0, 500) pw.setYRange(0, 22) s = pg.ScatterPlotItem() pw.addItem(s) pw.show() x = 0 while True: group = [int(port.read()[0]) for i in range(6)] s.addPoints(x = x, y = group) pg.QtGui.QApplication.processEvents() x += 1 if x == 500:
#!/usr/bin/env python import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore from subs import create_object rc = create_object() rc.loadenergies() bd = pg.mkPen(width=2, color=(200, 200, 255), style=QtCore.Qt.DotLine) plotWidget = pg.plot(title="Change in energies for " + rc.dirname, labels={ 'left': 'dE', 'bottom': 'twci' }) plotWidget.addLegend() plotWidget.plot(rc.t, rc.eges - rc.eges[0], pen=bd, name='dE_{tot}') plotWidget.plot(rc.t, rc.eb - rc.eb[0], pen=20, name='dE_{b} ') plotWidget.plot(rc.t, rc.eip - rc.eip[0], pen=30, name='dE_{ip} ') plotWidget.plot(rc.t, rc.eep - rc.eep[0], pen=40, name='dE_{ep} ') plotWidget.plot(rc.t, rc.eif - rc.eif[0], pen=50, name='dE_{if} ') plotWidget.plot(rc.t, rc.eef - rc.eef[0], pen=60, name='dE_{ef} ') plotWidget.plot(rc.t, rc.ee - rc.ee[0], pen=70, name='dE_{ee} ') QtGui.QApplication.instance().exec_()
# -*- coding: utf-8 -*- """ Demonstrates selecting plot curves by mouse click """ import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np win = pg.plot() win.setWindowTitle('pyqtgraph example: Plot data selection') curves = [ pg.PlotCurveItem(y=np.sin(np.linspace(0, 20, 1000)), pen='r', clickable=True), pg.PlotCurveItem(y=np.sin(np.linspace(1, 21, 1000)), pen='g', clickable=True), pg.PlotCurveItem(y=np.sin(np.linspace(2, 22, 1000)), pen='b', clickable=True), ] def plotClicked(curve): global curves for i,c in enumerate(curves): if c is curve: c.setPen('rgb'[i], width=3) else: c.setPen('rgb'[i], width=1) for c in curves: win.addItem(c) c.sigClicked.connect(plotClicked) ## Start Qt event loop unless running in interactive mode or using pyside.
import pyqtgraph as pg import numpy as np x = np.random.normal(size=1000) y = np.random.normal(size=1000) pg.plot(x, y, pen=None, symbol='o') Z = 1
logging.basicConfig(filename="test.log",format='%(asctime)s - %(levelname)s : %(message)s',level=logging.DEBUG) logging.info('---------LOG START-------------') board = bci.OpenBCIBoard(port=port, scaled_output=True, log=True, filter_data = False) print("Board Instantiated") board.ser.write('v') #tme.sleep(10) if not board.streaming: board.ser.write(b'b') board.streaming = True print("Samplerate: %0.2fHz" %board.getSampleRate()) #Graph setup app = QtGui.QApplication([]) p = pg.plot() nPlots = 8 nSamples = 2000 p.setWindowTitle('pyqtgraph example: MultiPlotSpeedTest') #p.setRange(QtCore.QRectF(0, -10, 5000, 20)) p.setLabel('bottom', 'Index', units='B') #curves = [p.plot(pen=(i,nPlots*1.3)) for i in range(nPlots)] curves = [] ptr = 0 lastTime = time() fps = None count = 0 data = [],[],[],[],[],[],[],[] rawdata = [],[],[],[],[],[],[],[] averagedata = [],[],[],[],[],[],[],[],[],[],[]
def computeParameters(self, dt_audio=1/80000, dt_video=1/4000, debug=False): """Compute parameters from GAW :param dt_audio: audio sampling time in seconds, defaults to 1/80000 :type dt_audio: float, optional :param dt_video: video sampling time in seconds, defaults to 1/4000 :type dt_video: float, optional :param debug: shows debugging information and plots, defaults to False :type debug: bool, optional """ # Convert raw segmentations to binary masks seg = np.asarray(self.segmentations).round().astype(np.bool) # Predict midline from segmentation M = Midline(seg) M.predict() # Use midline for left and right GAW gaws = M.side() left_gaw = gaws[..., 0] right_gaw = gaws[..., 1] # Compute and show values gaw = GAW(seg.sum((1,2)), use_filtered_signal=False, use_hanning=False, dt=dt_video) gaw.setLeftRightGAW(left_gaw, right_gaw) params_GAW = gaw.computeParameters() # Create summary table for parameters self.t = Table(params_GAW, title="GAW parameters") self.t.show() if debug: # Show complete segmentation with midline im = pg.image(seg.transpose(0, 2, 1), title="Segmentation with midline") line = pg.LineSegmentROI([M.coordinates[0, :2], M.coordinates[0, 2:],], pen="y") im.getView().addItem(line) # Show complete GAW plot with detected cycles gaw_plot = pg.plot(gaw.t, gaw.raw_signal, title="GAW with cycles") cs = [(241, 196, 15), (231, 76, 60)] i = 0 for o, c in zip(gaw.opening, gaw.closing): i1 = pg.PlotCurveItem(gaw.t[o:c], np.zeros_like(gaw.t[o:c])) i2 = pg.PlotCurveItem(gaw.t[o:c], gaw.raw_signal[o:c]) between = pg.FillBetweenItem(i1, i2, brush=cs[i % len(cs)]) gaw_plot.getPlotItem().addItem(between) i += 1 # Show left and right gaw LR_plot = pg.plot(title="Left and right GAW") LR_plot.plot(gaw.t, left_gaw) LR_plot.plot(gaw.t, -right_gaw) # Compute and show phonovibrogram pvg = M.pvg() pg.image(pvg, title="Phonovibrogram") # If audio data is available if type(self.synced_audio) != type(None): if debug: pg.plot(self.synced_audio, title="Synchronized audio") a = Audio(self.synced_audio, dt=dt_audio) params_Audio = a.computeParameters() self.t2 = Table(params_Audio, title="Audio parameters") self.t2.show() else: params_Audio = None return dict(GAW=params_GAW, Audio=params_Audio)
import pyqtgraph as pg import pyqtgraph.exporters import numpy as np print np.random.normal(size=100) plt = pg.plot(np.random.normal(size=100), title="Simplest possible plotting example") ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if sys.flags.interactive != 1 or not hasattr(pg.QtCore, 'PYQT_VERSION'): pg.QtGui.QApplication.exec_()
def plot_response_averages(expt, show_baseline=False, **kwds): analyzer = MultiPatchExperimentAnalyzer.get(expt) devs = analyzer.list_devs() # First get average evoked responses for all pre/post pairs responses, rows, cols = analyzer.get_evoked_response_matrix(**kwds) # resize plot grid accordingly plots = PlotGrid() plots.set_shape(len(rows), len(cols)) plots.show() ranges = [([], []), ([], [])] points = [] # Plot each matrix element with PSP fit for i, dev1 in enumerate(rows): for j, dev2 in enumerate(cols): # select plot and hide axes plt = plots[i, j] if i < len(devs) - 1: plt.getAxis('bottom').setVisible(False) if j > 0: plt.getAxis('left').setVisible(False) if dev1 == dev2: plt.getAxis('bottom').setVisible(False) plt.getAxis('left').setVisible(False) continue # adjust axes / labels plt.setXLink(plots[0, 0]) plt.setYLink(plots[0, 0]) plt.addLine(x=10e-3, pen=0.3) plt.addLine(y=0, pen=0.3) plt.setLabels(bottom=(str(dev2), 's')) if kwds.get('clamp_mode', 'ic') == 'ic': plt.setLabels(left=('%s' % dev1, 'V')) else: plt.setLabels(left=('%s' % dev1, 'A')) # print "==========", dev1, dev2 avg_response = responses[(dev1, dev2)].bsub_mean() if avg_response is not None: avg_response.t0 = 0 t = avg_response.time_values y = bessel_filter(Trace(avg_response.data, dt=avg_response.dt), 2e3).data plt.plot(t, y, antialias=True) # fit! #fit = responses[(dev1, dev2)].fit_psp(yoffset=0, mask_stim_artifact=(abs(dev1-dev2) < 3)) #lsnr = np.log(fit.snr) #lerr = np.log(fit.nrmse()) #color = ( #np.clip(255 * (-lerr/3.), 0, 255), #np.clip(50 * lsnr, 0, 255), #np.clip(255 * (1+lerr/3.), 0, 255) #) #plt.plot(t, fit.best_fit, pen=color) ## plt.plot(t, fit.init_fit, pen='y') #points.append({'x': lerr, 'y': lsnr, 'brush': color}) #if show_baseline: ## plot baseline for reference #bl = avg_response.meta['baseline'] - avg_response.meta['baseline_med'] #plt.plot(np.arange(len(bl)) * avg_response.dt, bl, pen=(0, 100, 0), antialias=True) # keep track of data range across all plots ranges[0][0].append(y.min()) ranges[0][1].append(y.max()) ranges[1][0].append(t[0]) ranges[1][1].append(t[-1]) plots[0,0].setYRange(min(ranges[0][0]), max(ranges[0][1])) plots[0,0].setXRange(min(ranges[1][0]), max(ranges[1][1])) # scatter plot of SNR vs NRMSE plt = pg.plot() plt.setLabels(left='ln(SNR)', bottom='ln(NRMSE)') plt.plot([p['x'] for p in points], [p['y'] for p in points], pen=None, symbol='o', symbolBrush=[pg.mkBrush(p['brush']) for p in points]) # show threshold line line = pg.InfiniteLine(pos=[0, 6], angle=180/np.pi * np.arctan(1)) plt.addItem(line, ignoreBounds=True) return plots
from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg p6 = pg.plot(title="Updating plot") curve = p6.plot(pen='y') data = np.random.normal(size=(10, 1000)) ptr = 0 def update(): global curve, data, ptr, p6 curve.setData(data[ptr % 10]) if ptr == 0: p6.enableAutoRange( 'xy', False) ## stop auto-scaling after the first data set is plotted ptr += 1 timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(50) QtGui.QApplication.instance().exec_()