我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用pyqtgraph.plot()。
def setup(self): #provide all parameters as floats with at least one decimal point self.frequency = 250.0 self.sample_interval = 1/self.frequency #converting to milliseconds for timer.start() function self.timer_interval = self.sample_interval*1000 self.time_window = 10 self.buffer_size = int(self.time_window/self.sample_interval) self.data_buffer = collections.deque([0.0]*self.buffer_size,self.buffer_size) self.x = np.linspace(0.0,self.time_window,self.buffer_size) self.y = np.zeros(self.buffer_size, dtype=np.float) #PyQtGraph settings self.app = QtGui.QApplication([]) self.plt = pg.plot(title='Real Time Open BCI data') self.plt.showGrid(x=True, y=True) self.plt.setLabel('left','amplitude','uV') self.plt.setLabel('bottom','time','s') self.curve = self.plt.plot(self.x,self.y,pen=(255,0,0)) #QTimer self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update_plot) self.timer.start(self.timer_interval)
def update_plot(self): self.cycle += 1 if self.cycle == 1: self.starttime = time.time() if self.cycle == self.cycles: self.endtime = time.time() if self.REDPITAYA: t = self.r.scope.times #y1 = self.r.scope.curve(ch=1, timeout=0) #y2 = self.r.scope.curve(ch=2, timeout=0) #self.r.scope.setup() y1 = self.r.scope._data_ch1_current y2 = self.r.scope._data_ch2_current else: t = self.t0 + (time.time()-self.starttime) phi = 2.0*np.pi*self.frequency*t y1 = np.sin(phi) y2 = np.cos(phi) if self.cycle == 1: self.c1 = self.plotWidget.plot(t, y1, pen='g') self.c2 = self.plotWidget.plot(t, y2, pen='r') else: self.c1.setData(t, y1) self.c2.setData(t, y2)
def updatePlot(self): # Lists for positions of cars x=[] y=[] color = [] carSymbol = [] for car in Plotter.instance()._trafficManager.cars: x.append(car.getPosition()) y.append((car.getLane() * self._laneWidth) - (self._laneWidth/2.)) color.append(pg.mkBrush(car.getColor())) if (car.getType() == 'b'): carSymbol.append('d') elif (car.getType() == 's'): carSymbol.append('o') elif (car.getType() == 'a'): carSymbol.append('+') else: carSymbol.append('t') self._pw.plot(x, y, clear=True, pen=None, symbol=carSymbol, symbolSize=20, symbolBrush = color) self._pw.addItem(self._backgroundImage) self._backgroundImage.setZValue(-100) # make sure image is behind other data self._backgroundImage.setRect(pg.QtCore.QRectF(0, 0, self._roadLength, self._roadWidth)) pg.QtGui.QApplication.processEvents()
def __init__(self, data, title = None, color = 'viridis', ncolors = None): #self.app = pg.QtGui.QApplication([]) #self.win = pg.GraphicsLayoutWidget() #self.win.resize(1200, 800) lut = colormap_lut(color, ncolors); self.img = pg.ImageItem() self.img.setLookupTable(lut) self.img.setLevels([0,1]) #self.plot = self.win.addPlot() self.plot = pg.plot(title = title); self.plot.addItem(self.img) #self.timer = QtCore.QTimer() #self.timer.timeout.connect(self.check_for_new_data_and_replot) #self.timer.start(100) self.img.setImage(data.T) #self.win.show()
def plot_tsne(data, analyse = True, n_components = 2, precomputed = False): """Perform t-SNE and plot overview of the results""" if precomputed: metric = 'precomputed'; else: metric = None; if analyse: tsne = sl.TSNE(n_components=n_components, init = 'pca', random_state = 0, metric = metric) Y = tsne.fit_transform(data) else: Y = data; if n_components == 1: plt.plot(Y); elif n_components == 2: plt.scatter(Y[:,0], Y[:,1], c = range(len(Y[:,0])), cmap = plt.cm.Spectral); else: ax = plt.gcf().add_subplot(1, 1, 1, projection = '3d'); ax.scatter(Y[:, 0], Y[:, 1], Y[:,2], c = range(len(Y[:,0])), cmap=plt.cm.Spectral) plt.title("t-SNE") plt.tight_layout();
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.assertTrue(np.allclose(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_temporal_derive(self): b_desired = 0.4 k = 5 # = k1 + k2 k1, k2, b = ut.split_domain(k, b_desired, self.l, mode='coprime')[0:3] # q E = tr.coefficient_recursion(self.y, self.beta*self.y, self.param) q = tr.temporal_derived_power_series(self.l-b, E, int(self.n_y/2)-1, self.n_y) # u B = tr.coefficient_recursion(self.y, self.alpha*self.y, self.param) xq = tr.temporal_derived_power_series(self.l, B, int(self.n_y/2)-1, self.n_y, spatial_der_order=0) d_xq = tr.temporal_derived_power_series(self.l, B, int(self.n_y/2)-1, self.n_y, spatial_der_order=1) u = d_xq + self.beta*xq # x(0,t) C = tr.coefficient_recursion(q, self.beta*q, self.param) D = tr.coefficient_recursion(np.zeros(u.shape), u, self.param) x_0t = tr.power_series(0, self.t, C) if show_plots: pw = pg.plot(title="control_input") pw.plot(self.t, x_0t) app.exec_()
def _update_plot(self): """ update plot window """ for idx, data_set in enumerate(self._data): # find nearest time index t_idx = ut.find_nearest_idx(self.time_data[idx], self._t) # TODO draw grey line if value is outdated # update data self._plot_data_items[idx].setData(x=self.spatial_data[idx], y=self.state_data[idx][t_idx]) self._time_text.setText('t= {0:.2f}'.format(self._t)) self._t += self._dt if self._t > self._endtime: self._t = 0
def test_InfiniteLine(): # Test basic InfiniteLine API plt = pg.plot() plt.setXRange(-10, 10) plt.setYRange(-10, 10) plt.resize(600, 600) # seemingly arbitrary requirements; might need longer wait time for some platforms.. QtTest.QTest.qWaitForWindowShown(plt) QtTest.QTest.qWait(100) vline = plt.addLine(x=1) assert vline.angle == 90 br = vline.mapToView(QtGui.QPolygonF(vline.boundingRect())) assert br.containsPoint(pg.Point(1, 5), QtCore.Qt.OddEvenFill) assert not br.containsPoint(pg.Point(5, 0), QtCore.Qt.OddEvenFill) hline = plt.addLine(y=0) assert hline.angle == 0 assert hline.boundingRect().contains(pg.Point(5, 0)) assert not hline.boundingRect().contains(pg.Point(0, 5)) vline.setValue(2) assert vline.value() == 2 vline.setPos(pg.Point(4, -5)) assert vline.value() == 4 oline = pg.InfiniteLine(angle=30) plt.addItem(oline) oline.setPos(pg.Point(1, -1)) assert oline.angle == 30 assert oline.pos() == pg.Point(1, -1) assert oline.value() == [1, -1] # test bounding rect for oblique line br = oline.mapToScene(oline.boundingRect()) pos = oline.mapToScene(pg.Point(2, 0)) assert br.containsPoint(pos, QtCore.Qt.OddEvenFill) px = pg.Point(-0.5, -1.0 / 3**0.5) assert br.containsPoint(pos + 5 * px, QtCore.Qt.OddEvenFill) assert not br.containsPoint(pos + 7 * px, QtCore.Qt.OddEvenFill)
def test_CSVExporter(): tempfilename = tempfile.NamedTemporaryFile(suffix='.csv').name print("using %s as a temporary file" % tempfilename) 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=tempfilename) r = csv.reader(open(tempfilename, '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 os.unlink(tempfilename)
def __init__(self, size=(600,350)): streams = resolve_byprop('name', 'bci', timeout=2.5) try: self.inlet = StreamInlet(streams[0]) except IndexError: raise ValueError('Make sure stream name=bci is opened first.') self.running = True self.frequency = 250.0 self.sampleinterval = (1/self.frequency) self.timewindow = 10 self._bufsize = int(self.timewindow/self.sampleinterval) self.dataBuffer = collections.deque([0.0] * self._bufsize, self._bufsize) self.timeBuffer = collections.deque([0.0] * self._bufsize, self._bufsize) self.x = np.empty(self._bufsize,dtype='float64') self.y = np.empty(self._bufsize,dtype='float64') self.app = QtGui.QApplication([]) self.plt = pg.plot(title='EEG data from OpenBCI') self.plt.resize(*size) self.plt.showGrid(x=True,y=True) self.plt.setLabel('left','Amplitude','V') self.plt.setLabel('bottom','Time','s') self.curve = self.plt.plot(self.x,self.y,pen=(255,0,0)) self.sample = np.zeros(8) self.timestamp = 0.0 #QTimer self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update) self.timer.start(self.sampleinterval)
def setup(self): self.t0 = np.linspace(0, self.duration, self.N) self.plotWidget = pg.plot(title="Realtime plotting benchmark") self.cycle = 0 self.starttime = time.time() # not yet the actual starttime, but needed for timeout if self.REDPITAYA: self.r.scope.setup(trigger_source='immediately', duration=self.duration) self.timer = QtCore.QTimer() self.timer.setInterval(1000*self.dt) self.timer.timeout.connect(self.update_plot) self.timer.start()
def plot_data(data, scroll_axis=2): """ Plot an image associated data. Currently support on 1D, 2D or 3D data. Parameters ---------- data: array the data to be displayed. scroll_axis: int (optional, default 2) the scroll axis for 3d data. """ # Check input parameters if data.ndim not in range(1, 4): raise ValueError("Unsupported data dimension.") # Deal with complex data if numpy.iscomplex(data).any(): data = numpy.abs(data) # Create application app = pyqtgraph.mkQApp() # Create the widget if data.ndim == 3: indices = [i for i in range(3) if i != scroll_axis] indices = [scroll_axis] + indices widget = pyqtgraph.image(numpy.transpose(data, indices)) elif data.ndim == 2: widget = pyqtgraph.image(data) else: widget = pyqtgraph.plot(data) # Run application app.exec_()
def __init__(self): self._backgroundImage = "../roadlanes.png" self._roadLength = 5e4 self._roadWidth = self._roadLength * 663./1657 self._laneWidth = self._roadWidth / 4. self._trafficManager = None self._pw = pg.plot(pen='y', symbol='t', symbolSize=200) x = Image.open('../roadlanes.png') im = np.array(x) self._backgroundImage = pg.ImageItem(im, autoDownsample = True, autoLevels = False)
def __init__(self, points, title = None): pg.mkQApp(); self.w = gl.GLViewWidget() self.w.opts['distance'] = 20 self.w.show() self.w.setWindowTitle(title) self.g = gl.GLGridItem() self.w.addItem(self.g) self.sp = gl.GLScatterPlotItem(pos=points, color=(1,1,1,1), pxMode= True) self.w.addItem(self.sp); #self.plot.addItem(self.w); # ### create three grids, add each to the view #xgrid = gl.GLGridItem() #ygrid = gl.GLGridItem() #zgrid = gl.GLGridItem() #view.addItem(xgrid) #view.addItem(ygrid) #view.addItem(zgrid) # ### rotate x and y grids to face the correct direction #xgrid.rotate(90, 0, 1, 0) #ygrid.rotate(90, 1, 0, 0) # ### scale each grid differently #xgrid.scale(0.2, 0.1, 0.1) #ygrid.scale(0.2, 0.1, 0.1) #zgrid.scale(0.1, 0.2, 0.1)
def savefig(plot, filename, width = None): """Export plot to file""" exporter = pgexp.ImageExporter(plot.img); if width is not None: exporter.parameters()['width'] = width # (note this also affects height parameter) # save to file exporter.export(filename)
def plot_distributions(data, cmap = plt.cm.Spectral_r, percentiles = [5, 25, 50, 75, 95], percentiles_colors = ['gray', 'gray', 'red', 'gray', 'gray']): """Plots the data point color as local density""" npoints, ntimes = data.shape; for t in range(ntimes): cols = gaussian_kde(data[:,t])(data[:,t]); idx = cols.argsort(); plt.scatter(np.ones(npoints)*t, data[idx,t], c=cols[idx], s=30, edgecolor='face', cmap = cmap) pct = np.percentile(data, percentiles, axis = 0); for i in range(len(percentiles)): #plt.plot(iqr[s0][i,:], c = plt.cm.Spectral(i/5.0), linewidth = 3); plt.plot(pct[i,:], c = percentiles_colors[i], linewidth = 2);
def plot_nmf(data, analyse = True, n_components = 2): """Perform NMF and plot overview of the results""" if analyse: nmf = sd.NMF(n_components=n_components, init = 'nndsvdar', random_state = 0, solver = 'cd') Y = nmf.fit_transform(data) else: Y = data; nmf = None; if n_components is None: n_components = 3; if n_components == 1: plt.subplot(1,3,1); plt.plot(Y); elif n_components == 2: plt.subplot(1,3,1); plt.scatter(Y[:,0], Y[:,1], c = range(len(Y[:,0])), cmap = plt.cm.Spectral); else: ax = plt.gcf().add_subplot(1,3,1, projection = '3d'); ax.scatter(Y[:, 0], Y[:, 1], Y[:,2], c = range(len(Y[:,0])), cmap=plt.cm.Spectral) plt.title("nmf") if nmf is not None: feat = nmf.components_; plt.subplot(1,3,2); plt.imshow(feat, interpolation = 'none', aspect = 'auto', cmap = 'viridis') plt.colorbar(pad = 0.01,fraction = 0.01) plt.title('features'); plt.subplot(1,3,3); plt.imshow(Y, interpolation = 'none', aspect = 'auto', cmap = 'viridis') plt.colorbar(pad = 0.01,fraction = 0.01) plt.title('amplitudes'); plt.tight_layout();
def plot_embedding_contours(Y, contours = 10, cmap = plt.cm.plasma, xmin = None, xmax = None, ymin = None, ymax = None, npts = 100, density = False): """Plot a 2d density map of the embedding Y""" if xmin is None: xmin = np.min(Y[:,0]); if xmax is None: xmax = np.max(Y[:,0]); if ymin is None: ymin = np.min(Y[:,1]); if ymax is None: ymax = np.max(Y[:,1]); #print xmin,xmax,ymin,ymax dx = float(xmax-xmin) / npts; dy = float(xmax-xmin) / npts; xx, yy = np.mgrid[xmin:xmax:dx, ymin:ymax:dy] positions = np.vstack([xx.ravel(), yy.ravel()]) kernel = st.gaussian_kde(Y.T); #print xx.shape #print positions.shape #print Y.shape #print kernel(positions).shape f = kernel(positions) f = np.reshape(f, xx.shape) #print f.shape ax = plt.gca() ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # Contourf plot if density: cfset = ax.contourf(xx, yy, f, cmap=cmap) ## Or kernel density estimate plot instead of the contourf plot #ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax]) # Contour plot if contours is not None: cset = ax.contour(xx, yy, f, contours, cmap=cmap) # Label plot #ax.clabel(cset, inline=1, fontsize=10) ax.set_xlabel('Y0') ax.set_ylabel('Y1')
def test(): import numpy as np import plot as p; reload(p) data = np.random.rand(100,200); p.plot(data, 'test') reload(p) pts = np.random.rand(10000,3); p.plot3d(pts);
def plot_pca(data, analyse = True): """Performs PCA and plots an overview of the results""" if analyse: results = PCA(data); else: results = data; #results = PCA(X); pcs = results.Y; plt.subplot(1,3,1); plt.imshow(pcs, interpolation = 'none', aspect = 'auto', cmap = 'viridis') plt.colorbar(pad = 0.01,fraction = 0.01) plt.title('pca components'); plt.subplot(2,3,2); plt.imshow(results.Wt, cmap = 'magma', interpolation = 'none' ); plt.colorbar(pad = 0.01,fraction = 0.01) plt.title('pca vectors') ax = plt.gcf().add_subplot(2,3,5, projection = '3d'); ax.plot(pcs[:,0], pcs[:,1], pcs[:,2], 'k'); ax.scatter(pcs[:,0], pcs[:,1], pcs[:,2], 'bo', c = range(len(pcs[:,0])), cmap = plt.cm.Spectral ); plt.xlabel('PCA1'); plt.ylabel('PCA2'); ax.set_zlabel('PCA3'); plt.subplot(2,3,3); plt.plot(results.mu) plt.title('mean'); plt.subplot(2,3,6); plt.plot(np.cumsum(results.fracs), 'r') plt.title('variance explained') plt.tight_layout(); return results;
def test_back_projection_from_lagrange_1st(self): vec_real_func = np.vectorize(self.funcs[1]) real_weights = vec_real_func(self.nodes) approx_func = core.back_project_from_base(real_weights, self.initial_functions) approx_func_dz = core.back_project_from_base(real_weights, get_base("ini_funcs", 1)) self.assertTrue(np.allclose(approx_func(self.z_values), vec_real_func(self.z_values))) if show_plots: # lines should match exactly pw = pg.plot(title="back projected linear function") pw.plot(x=self.z_values, y=vec_real_func(self.z_values), pen="r") pw.plot(x=self.z_values, y=approx_func(self.z_values), pen="g") pw.plot(x=self.z_values, y=approx_func_dz(self.z_values), 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 test_trajectory(self): # build flatness based trajectory generator fs = tr.FlatString(y0=self.y0, y1=self.y1, z0=self.z_start, z1=self.z_end, t0=self.t_start, dt=2, params=self.params) zz, tt = np.meshgrid(self.z_values, self.t_values) x_values = fs.system_state(zz, tt) u_values = fs.control_input(self.t_values) eval_data_x = vis.EvalData([self.t_values, self.z_values], x_values) if show_plots: # plot stuff pw = pg.plot(title="control_input") pw.plot(self.t_values, u_values) ap = vis.PgAnimatedPlot(eval_data_x) app.exec_()
def __init__(self, t, u, show_plot=False): SimulationInput.__init__(self) self._t = t self._T = t[-1] self._u = u self.scale = 1 if show_plot: pw = pg.plot(title="InterpTrajectory") pw.plot(self._t, self.__call__(time=self._t)) pw.plot([0, self._T], self.__call__(time=[0, self._T]), pen=None, symbolPen=pg.mkPen("g")) pg.QtGui.QApplication.instance().exec_()
def __init__(self, data, title="", dt=None): PgDataPlot.__init__(self, data) self.time_data = [np.atleast_1d(data_set.input_data[0]) for data_set in self._data] self.spatial_data = [np.atleast_1d(data_set.input_data[1]) for data_set in self._data] self.state_data = [data_set.output_data for data_set in self._data] self._pw = pg.plot(title=time.strftime("%H:%M:%S") + ' - ' + title) self._pw.addLegend() self._pw.showGrid(x=True, y=True, alpha=0.5) max_times = [max(data) for data in self.time_data] self._endtime = max(max_times) self._longest_idx = max_times.index(self._endtime) if dt is not None: self._dt = dt spat_min = np.min([np.min(data) for data in self.spatial_data]) spat_max = np.max([np.max(data) for data in self.spatial_data]) self._pw.setXRange(spat_min, spat_max) state_min = np.min([np.min(data) for data in self.state_data]) state_max = np.max([np.max(data) for data in self.state_data]) self._pw.setYRange(state_min, state_max) self._time_text = pg.TextItem('t= 0') self._pw.addItem(self._time_text) self._time_text.setPos(.9 * spat_max, .9 * state_min) self._plot_data_items = [] for idx, data_set in enumerate(self._data): self._plot_data_items.append(pg.PlotDataItem(pen=colors[idx], name=data_set.name)) self._pw.addItem(self._plot_data_items[-1]) self._curr_frame = 0 self._t = 0 self._timer = pg.QtCore.QTimer() self._timer.timeout.connect(self._update_plot) self._timer.start(1e3 * self._dt)
def __init__(self, data, title=None): PgDataPlot.__init__(self, data) self.dim = self._data[0].output_data.shape self.win = pg.QtGui.QMainWindow() self.win.resize(800, 800) self.win.setWindowTitle("PgSlicePlot: {}".format(title)) self.cw = pg.QtGui.QWidget() self.win.setCentralWidget(self.cw) self.l = pg.QtGui.QGridLayout() self.cw.setLayout(self.l) self.image_view = pg.ImageView(name="img_view") self.l.addWidget(self.image_view, 0, 0) self.slice_view = pg.PlotWidget(name="slice") self.l.addWidget(self.slice_view) self.win.show() # self.imv2 = pg.ImageView() # self.l.addWidget(self.imv2, 1, 0) self.roi = pg.LineSegmentROI([[0, self.dim[1] - 1], [self.dim[0] - 1, self.dim[1] - 1]], pen='r') self.image_view.addItem(self.roi) self.image_view.setImage(self._data[0].output_data) # # self.plot_window.showGrid(x=True, y=True, alpha=.5) # self.plot_window.addLegend() # # input_idx = 0 if self.data_slice.shape[0] > self.data_slice.shape[1] else 0 # for data_set in data: # self.plot_window.plot(data_set.input_data[input_idx], data_set.output_data[self.data_slice], # name=data.name) # TODO: alpha
def update(): global line1, line2 data = i.get_realtime_data() # Update the plot line1.setData(data.time, data.ch1) line2.setData(data.time, data.ch2)
def test_mouseInteraction(): plt = pg.plot() plt.scene().minDragTime = 0 # let us simulate mouse drags very quickly. vline = plt.addLine(x=0, movable=True) plt.addItem(vline) hline = plt.addLine(y=0, movable=True) hline2 = plt.addLine(y=-1, movable=False) plt.setXRange(-10, 10) plt.setYRange(-10, 10) # test horizontal drag pos = plt.plotItem.vb.mapViewToScene(pg.Point(0,5)).toPoint() pos2 = pos - QtCore.QPoint(200, 200) mouseMove(plt, pos) assert vline.mouseHovering is True and hline.mouseHovering is False mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton) px = vline.pixelLength(pg.Point(1, 0), ortho=True) assert abs(vline.value() - plt.plotItem.vb.mapSceneToView(pos2).x()) <= px # test missed drag pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,0)).toPoint() pos = pos + QtCore.QPoint(0, 6) pos2 = pos + QtCore.QPoint(-20, -20) mouseMove(plt, pos) assert vline.mouseHovering is False and hline.mouseHovering is False mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton) assert hline.value() == 0 # test vertical drag pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,0)).toPoint() pos2 = pos - QtCore.QPoint(50, 50) mouseMove(plt, pos) assert vline.mouseHovering is False and hline.mouseHovering is True mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton) px = hline.pixelLength(pg.Point(1, 0), ortho=True) assert abs(hline.value() - plt.plotItem.vb.mapSceneToView(pos2).y()) <= px # test non-interactive line pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,-1)).toPoint() pos2 = pos - QtCore.QPoint(50, 50) mouseMove(plt, pos) assert hline2.mouseHovering == False mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton) assert hline2.value() == -1
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; # legs = []; # for k,i in enumerate(uids): # ii = np.where(ids == i)[0]; # if depth > 0: # ii = [ii-d for d in range(depth)]; # ii = np.unique(np.concatenate(ii)); # # plt.plot(data[ii, 0], data[ii, 1], '.', color = color[k]); # # legs.append(mpatches.Patch(color=color[k], label= str(i))); # # plt.legend(handles=legs);
def plot_embedding_contours(Y, contours = 10, cmap = 'plasma', xmin = None, xmax = None, ymin = None, ymax = None, npts = 100, density = False): """Plot a 2d density map of the embedding Y""" if xmin is None: xmin = np.min(Y[:,0]); if xmax is None: xmax = np.max(Y[:,0]); if ymin is None: ymin = np.min(Y[:,1]); if ymax is None: ymax = np.max(Y[:,1]); #print xmin,xmax,ymin,ymax dx = float(xmax-xmin) / npts; dy = float(ymax-ymin) / npts; xx, yy = np.mgrid[xmin:xmax:dx, ymin:ymax:dy] positions = np.vstack([xx.ravel(), yy.ravel()]) kernel = st.gaussian_kde(Y.T); #print xx.shape #print positions.shape #print Y.shape #print kernel(positions).shape f = kernel(positions) f = np.reshape(f, xx.shape) #print f.shape ax = plt.gca() ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # Contourf plot if density: cfset = ax.contourf(xx, yy, f, cmap=cmap) ## Or kernel density estimate plot instead of the contourf plot #ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax]) # Contour plot if contours is not None: cset = ax.contour(xx, yy, f, contours, cmap=cmap) # Label plot #ax.clabel(cset, inline=1, fontsize=10) ax.set_xlabel('Y0') ax.set_ylabel('Y1') return (kernel, f)
def shape_generator(self, cls, der_order): """ verify the correct connection with visual feedback """ dz = pi.Domain((0, 1), step=.001) dt = pi.Domain((0, 0), num=1) nodes, funcs = pi.cure_interval(cls, dz.bounds, node_count=11) pi.register_base("test", funcs, overwrite=True) # approx_func = pi.Function(np.cos, domain=dz.bounds, # derivative_handles=[lambda z: -np.sin(z), lambda z: -np.cos(z)]) approx_func = pi.Function(lambda z: np.sin(3*z), domain=dz.bounds, derivative_handles=[lambda z: 3*np.cos(3*z), lambda z: -9*np.sin(3*z)]) weights = approx_func(nodes) hull = pi.evaluate_approximation("test", np.atleast_2d(weights), temp_domain=dt, spat_domain=dz, spat_order=der_order) if show_plots: # plot shapefunctions c_map = pi.visualization.create_colormap(len(funcs)) pw = pg.plot(title="{}-Test".format(cls.__name__)) pw.addLegend() pw.showGrid(x=True, y=True, alpha=0.5) [pw.addItem(pg.PlotDataItem(np.array(dz), weights[idx]*func.derive(der_order)(dz), pen=pg.mkPen(color=c_map[idx]), name="{}.{}".format(cls.__name__, idx))) for idx, func in enumerate(funcs)] # plot hull curve pw.addItem(pg.PlotDataItem(np.array(hull.input_data[1]), hull.output_data[0, :], pen=pg.mkPen(width=2), name="hull-curve")) # plot original function pw.addItem(pg.PlotDataItem(np.array(dz), approx_func.derive(der_order)(dz), pen=pg.mkPen(color="m", width=2, style=pg.QtCore.Qt.DashLine), name="original")) pg.QtCore.QCoreApplication.instance().exec_() return np.sum(np.abs(hull.output_data[0, :] - approx_func.derive(der_order)(dz)))