def _get_range_curve(self): color = QColor(self.color) color.setAlpha(LinePlotStyle.RANGE_ALPHA) bottom, top = nanmin(self.y_data, axis=0), nanmax(self.y_data, axis=0) return pg.FillBetweenItem(pg.PlotDataItem(x=self.x_data, y=bottom), pg.PlotDataItem(x=self.x_data, y=top), brush=color)
def t_dependent_updates_laser_red_2(self): self.label_nu_red_2_is.setText(str(lc.nu_red_2_is)) # self.doubleSpinBox_nu_blue_1_want.setValue(lc.nu_blue_1_want) lc.lock_red_2_alpha = float( self.doubleSpinBox_lock_red_2_alpha.value()) lc.lock_red_2_beta = float(self.doubleSpinBox_lock_red_2_beta.value()) try: self.plot_nu_red_2.plot(np.arange(500), lc.nu_red_2_was[-500:], pen=blackPen, symbol='o', symbolBrush=redBrush, name='nu_red_2_was', clear=True) except Exception: pass nu_red_2_upper = pg.PlotCurveItem([0, 500], [350.862605, 350.862605], pen=redPen) nu_red_2_lower = pg.PlotCurveItem([0, 500], [350.862595, 350.862595], pen=redPen) nu_red_2_fill = pg.FillBetweenItem(nu_red_2_upper, nu_red_2_lower, redBrush_alpha) self.plot_nu_red_2.addItem(nu_red_2_upper) self.plot_nu_red_2.addItem(nu_red_2_lower) self.plot_nu_red_2.addItem(nu_red_2_fill)
def prepare_widget(self, widget): super(BarFeedbackProtocolWidgetPainter, self).prepare_widget(widget) self.p1 = widget.plot(self.x, np.zeros_like(self.x), pen=pg.mkPen(229, 223, 213)).curve self.p2 = widget.plot(self.x, np.zeros_like(self.x)-5, pen=pg.mkPen(229, 223, 213)).curve fill = pg.FillBetweenItem(self.p1, self.p2, brush=(229, 223, 213, 25)) self.fill = fill widget.addItem(fill)
def violin_plot(ax, data, pos, dist=.0, bp=False): ''' create violin plots on an axis ''' if data is None or len(data) == 0: return # skip trying to do the plot dist = max(pos) - min(pos) w = min(0.15 * max(dist, 1.0), 0.5) for i, d in enumerate(data): if d == [] or len(d) == 0: continue k = scipy.stats.gaussian_kde(d) #calculates the kernel density m = k.dataset.min() #lower bound of violin M = k.dataset.max() #upper bound of violin y = np.arange(m, M, (M - m) / 100.) # support for violin v = k.evaluate(y) #violin profile (density curve) v = v / v.max() * w #scaling the violin to the available space c1 = pg.PlotDataItem(y=y, x=pos[i] + v, pen=pg.mkPen('k', width=0.5)) c2 = pg.PlotDataItem(y=y, x=pos[i] - v, pen=pg.mkPen('k', width=0.5)) #mean = k.dataset.mean() #vm = k.evaluate(mean) #vm = vm * w #ax.plot(x=np.array([pos[i]-vm[0], pos[i]+vm[0]]), y=np.array([mean, mean]), pen=pg.mkPen('k', width=1.0)) ax.addItem(c1) ax.addItem(c2) #ax.addItem(hbar) f = pg.FillBetweenItem(curve1=c1, curve2=c2, brush=pg.mkBrush((255, 255, 0, 96))) ax.addItem(f) if bp: pass
def populateGraph(self): """ Processes subtraction data and populates the graph with the processed data """ dat = self.project.eg for analyte in self.project.eg.analytes: datapoints = self.getDatapoints(dat, analyte) # Add items to graph scatter = pg.ScatterPlotItem(dat.bkg['raw'].uTime, datapoints[0], pen=None, brush=pg.mkBrush(self.hex_2_rgba(dat.cmaps[analyte], 127)), size=3) self.graphScatters[analyte] = scatter line = pg.PlotDataItem(datapoints[1], datapoints[2], pen=pg.mkPen(dat.cmaps[analyte], width=2), label=analyte, name=analyte, connect='finite') self.graphLines[analyte] = line fill = pg.FillBetweenItem(pg.PlotDataItem(datapoints[1], datapoints[3], pen=pg.mkPen(0,0,0,0)), pg.PlotDataItem(datapoints[1], datapoints[4], pen=pg.mkPen(0,0,0,0)), brush=pg.mkBrush(self.hex_2_rgba(dat.cmaps[analyte], 204))) self.graphFills[analyte] = fill self.graphLines[analyte] = (scatter, line, fill) self.graph.addItem(scatter) self.graph.addItem(line) self.graph.addItem(fill) # Add/update highlighted sample regions to graph for s, d in dat.data.items(): self.addRegion(s, self.graph, (d.uTime[0], d.uTime[-1]), pg.mkBrush((0,0,0,25))) sampleLine = pg.InfiniteLine(pos=d.uTime[0], pen=pg.mkPen(color=(0,0,0,51), style=Qt.DashLine, width=2), label=s, labelOpts={'position': .999, 'anchors': ((0., 0.), (0., 0.))}) self.bkgSamplelines[d] = sampleLine self.graph.addItem(sampleLine) self.populated = True self.sampleList.setCurrentItem(self.sampleList.item(0))
def mkStick(self, low, high, start, end): goingup = False if start < end: goingup = True p = pg.mkPen(self.style['color'], width=self.style['lineWidth']) else: p = pg.mkPen(self.style['fillColor'], width=self.style['lineWidth']) b = pg.mkBrush(self.style['fillColor']) lx = self.baseX + self.style['gap'] mx = self.baseX + self.style['gap'] + self.style['width'] / 2 rx = self.baseX + self.style['gap'] + self.style['width'] self.baseX += self.style['gap'] + self.style['width'] if goingup == False: lb = pg.PlotCurveItem(x=[mx, mx, lx, lx, mx], y=[high, start, start, end, end], pen=p) # leff-bottom half rt = pg.PlotCurveItem(x=[mx, mx, rx, rx, mx], y=[low, end, end, start, start], pen=p) # right-top half fill = pg.FillBetweenItem(lb, rt, brush=b, pen=p) return [lb, rt, fill] else: stick = pg.PlotCurveItem( x=[mx, mx, lx, lx, mx, mx, mx, rx, rx, mx], y=[high, end, end, start, start, low, start, start, end, end], pen=p) return [stick]
def update_plots(self): self.plot.clear() args = self.args.copy() self.plot.plot(args['x'], self.data, antialias=True) args.update(self.initial_params()) self.plot.plot(args['x'], self.model.eval(y=self.data, **args), pen='y', antialias=True) if self.fit is not None: args.update(self.fit_params()) fity = self.model.eval(y=self.data, **args) self.plot.plot(args['x'], fity, pen='g', antialias=True) if hasattr(self.fit, 'eval_uncertainty'): # added in 0.9.6 try: err = self.fit.eval_uncertainty() c1 = pg.PlotCurveItem(args['x'], fity-err) c2 = pg.PlotCurveItem(args['x'], fity+err) fill = pg.FillBetweenItem(c1, c2, pg.mkBrush((0, 255, 0, 50))) self.plot.addItem(fill, ignoreBounds=True) fill.setZValue(-1) except Exception: # eval_uncertainty is broken in some versions pass self._update_fit_stats()
def _updatePercentile(self, grp, plt): self._dataLck.acquire() self._datas[grp][plt]["datas"] = {} if self._datas[grp][plt]["error"] is None: x = self._datas[grp][plt]["x"] for p, s in zip(self._datas[grp][plt]["pairs"], self._datas[grp][plt]["styles"]): c1 = pg.PlotDataItem(x, self._datas[grp][plt]["y"][p[0]], pen=s[0]) c2 = pg.PlotDataItem(x, self._datas[grp][plt]["y"][p[1]], pen=s[0]) f = pg.FillBetweenItem(c1, c2, s[1]) self._datas[grp][plt]["datas"][p] = [] self._datas[grp][plt]["datas"][p].append(c1) self._datas[grp][plt]["datas"][p].append(c2) self._datas[grp][plt]["datas"][p].append(f) self._dataLck.release() if not (self._list.currentItem() is None) and \ self._list.currentItem().data(Plotter.GRP_ROLE) == grp and \ self._list.currentItem().data(Plotter.PLT_ROLE) == plt : self._itemClicked(self._list.currentItem())
def graphAveragePlasticityByGroup(trials, group=1): """Trials is a numpy record array that might come from a database view. """ data = trials[trials['drug_group'] == group] cells = set(data['CellDir']) timebins = np.arange(0, 3300, 60) results = np.zeros((len(timebins), len(cells), 2)) for i, c in enumerate(cells): d = data[data['CellDir'] == c] results[:len(d), i, 0] = d['normalizedPspSlope'] results[:len(d), i, 1] = d['UseData'] avgSlope = np.ma.masked_array( results[:, :, 0], mask=~results[:, :, 1].astype(bool)).mean(axis=0) stdev = np.ma.masked_array(results[:, :, 0], mask=~results[:, :, 1].astype(bool)).std(axis=0) plot = pg.plot(timebins + 30, avgSlope) c1 = pg.PlotCurveItem(timebins + 30, avgSlope + stdev, 'r') c2 = pg.PlotCurveItem(timebins + 30, avgSlope - stdev, 'r') plot.addItem(pg.FillBetweenItem(c1, c2, brush=(255, 0, 0, 100))) return plot
def prepare_widget(self, widget): super(CircleFeedbackProtocolWidgetPainter, self).prepare_widget(widget) self.p1 = widget.plot(np.sin(self.x), np.cos(self.x), pen=pg.mkPen(229, 223, 213)).curve self.p2 = widget.plot(np.sin(self.x), -np.cos(self.x), pen=pg.mkPen(229, 223, 213)).curve fill = pg.FillBetweenItem(self.p1, self.p2, brush=(229, 223, 213, 25)) self.fill = fill widget.addItem(fill)
def setupProfileTab(self): plot = self.profilePlot plot.setXRange(0., self.maxrange) plot.showGrid(True, True, 0.2) plot.setLabel('bottom', 'r [pixel]') plot.setLabel('left', 'b(r)') pen = pg.mkPen('k', width=3, style=QtCore.Qt.DashLine) plot.addLine(y=1., pen=pen) pen = pg.mkPen('k', width=3) plot.getAxis('bottom').setPen(pen) plot.getAxis('left').setPen(pen) pen = pg.mkPen('r', width=3) self.theoryProfile = pg.PlotCurveItem(pen=pen) plot.addItem(self.theoryProfile) pen = pg.mkPen('k', width=3) self.dataProfile = pg.PlotCurveItem(pen=pen) plot.addItem(self.dataProfile) pen = pg.mkPen('k', width=1, style=QtCore.Qt.DashLine) self.regionUpper = pg.PlotCurveItem(pen=pen) self.regionLower = pg.PlotCurveItem(pen=pen) self.dataRegion = pg.FillBetweenItem(self.regionUpper, self.regionLower, brush=pg.mkBrush( 255, 165, 0, 128)) plot.addItem(self.dataRegion)
def _min_max_show(self): if not self._is_min_max_active: self._min_max_hide() return c = self._cmdp['Widgets/Waveform/show_min_max'] if c == 'lines': self.curve_max.show() self.curve_min.show() if self.curve_range is not None: curve_range, self.curve_range = self.curve_range, None self.vb.removeItem(curve_range) del curve_range elif c == 'fill': self.curve_max.hide() self.curve_min.hide() if self.curve_range is None: self.curve_range = pg.FillBetweenItem( self.curve_min, self.curve_max, brush=self._brush_min_max) self.vb.addItem(self.curve_range) else: self.curve_range.show() else: if c != 'off': self.log.warning( 'unsupported show_min_max mode: %s, presume "off"', c) self._min_max_hide()
def __init__(self, time, events, label=None, color=None): self._kmf = KaplanMeierFitter().fit(time.astype(np.float64), events.astype(np.float64)) self._label: str = label self.color: List[int] = color # refactor this time, survival = self._kmf.survival_function_.reset_index( ).values.T.tolist() lower, upper = self._kmf.confidence_interval_.values.T.tolist() self.x, self.y = self.generate_curve_coordinates(time, survival) _, self.lower_bound = self.generate_curve_coordinates(time, lower) _, self.upper_bound = self.generate_curve_coordinates(time, upper) # Estimated function curve self.estimated_fun = pg.PlotDataItem(self.x, self.y, pen=self.get_pen()) # Lower and upper confidence intervals pen = self.get_pen(width=1, alpha=70) self.lower_conf_limit = pg.PlotDataItem(self.x, self.lower_bound, pen=pen) self.upper_conf_limit = pg.PlotDataItem(self.x, self.upper_bound, pen=pen) self.confidence_interval = pg.FillBetweenItem( self.upper_conf_limit, self.lower_conf_limit, brush=self.get_color(alpha=50)) self.selection = pg.PlotDataItem( pen=mkPen(color=QColor(Qt.yellow), width=4)) self.selection.hide() self.median_survival = median = np.round( median_survival_times( self._kmf.survival_function_.astype(np.float32)), 1) self.median_vertical = pg.PlotDataItem( x=(median, median), y=(0, 0.5), pen=pg.mkPen(**MEDIAN_LINE_PEN_STYLE)) censored_data = self.get_censored_data() self.censored_data = pg.ScatterPlotItem( x=censored_data[:, 0], y=censored_data[:, 1], brush=QBrush(Qt.black), pen=self.get_pen(width=1, alpha=255), symbol=create_line_symbol(), size=15, ) self.censored_data.setZValue(10) self.num_of_samples = len(events) self.num_of_censored_samples = len(censored_data)
def __init__(self): super().__init__() self.plot = pg.PlotWidget() self.plot.addLegend(size=(80, 50)) self.curve_x = pg.PlotCurveItem(data[0], data[1], pen=pg.mkPen(color=(0x2E, 0x86, 0xAB), width=2), name='X') self.curve_y = pg.PlotCurveItem(data[0], data[2], pen=pg.mkPen(color=(0xF0, 0x87, 0x00), width=2), name='Y') self.curve_z = pg.PlotCurveItem(data[0], data[3], pen=pg.mkPen(color=(0x8A, 0xC9, 0x26), width=2), name='Z') self.curve_p = pg.PlotCurveItem(data[0], (1 - data[4]) * 5000, pen=pg.mkPen(color=(46, 40, 171), width=1)) self.fillLevel = pg.PlotCurveItem([0, data[0][-1]], [0, 0]) self.cut = pg.FillBetweenItem(curve1=self.curve_p, curve2=self.fillLevel, brush=pg.mkBrush(color=(0xFF, 0x64, 0x16, 80))) self.plot.addItem(self.curve_x) self.plot.addItem(self.curve_y) self.plot.addItem(self.curve_z) self.plot.addItem(self.cut) for event in events: self.marker = pg.InfiniteLine(pos=int(event[0]) * 10000, pen=pg.mkPen(color=(0xF0, 0x57, 0x00), width=1), label=event[1]) self.plot.addItem(self.marker) self.marker = pg.InfiniteLine(pos=data[0][-1], pen=pg.mkPen(color=(0xF0, 0x57, 0x00), width=1), movable=True, label='t : {value:.0f}') self.plot.addItem(self.marker) grid_alpha = 70 x = self.plot.getAxis("bottom") y = self.plot.getAxis("left") x.setGrid(grid_alpha) y.setGrid(grid_alpha) layout = QtGui.QVBoxLayout() layout.addWidget(self.plot) self.setLayout(layout)
def _get_range_curve(self): color = QColor(self.color) color.setAlpha(self.graph.range_settings[Updater.ALPHA_LABEL]) bottom, top = nanmin(self.y_data, axis=0), nanmax(self.y_data, axis=0) return pg.FillBetweenItem( pg.PlotDataItem(x=self.x_data, y=bottom), pg.PlotDataItem(x=self.x_data, y=top), brush=color )
def __init__(self, curve1=None, curve2=None, brush=None, pen=None): self.curve1 = curve1 self.curve2 = curve2 self.fbtwn_item = pg.FillBetweenItem(curve1=self.curve1, curve2=self.curve2, brush=brush, pen=None) for m in ["opts"]: setattr(self, m, getattr(self.curve1, m)) self.opts["fillBrush"] = self.fbtwn_item.brush() self.setPen(pen)
def draw_stats_graph(self): """ draw the statistics graph """ tick_font = qg.QFont() tick_font.setBold(True) levels = np.linspace(0.2, 1, 5) stats = self._data_source.get_video_stats() means = [x.mean for x in stats.frames] std_dev = [x.std_deviation for x in stats.frames] means_plus = [] means_minus = [] for i, mean in enumerate(means): means_plus.append(mean + std_dev[i]) means_minus.append(mean - std_dev[i]) self._graph.getAxis('left').setLabel( "Intensity (Level)", **VideoStatisticsWidget.label_style) self._graph.getAxis('left').setTickFont(tick_font) self._graph.getAxis('bottom').setLabel( "Frame (number)", **VideoStatisticsWidget.label_style) self._graph.getAxis('bottom').setTickFont(tick_font) self._graph.setYRange(0, 260) x_axis = range(1, len(stats.frames) + 1) self._graph.addLegend() m_plot = self._graph.plot(x_axis, means, pen='b', name="Mean") up_plot = self._graph.plot(x_axis, means_plus, pen='r', name="Std Dev up") down_plot = self._graph.plot(x_axis, means_minus, pen='r', name="Std Dev down") self._graph.addItem(pg.FillBetweenItem(m_plot, up_plot, levels[3])) self._graph.addItem(pg.FillBetweenItem(m_plot, down_plot, levels[3])) self._frame_line = pg.InfiniteLine(angle=90, movable=False) self._frame_line.setBounds([0, len(stats.frames)]) self._graph.addItem(self._frame_line)
def __init__(self, name, units=None, y_limit=None, y_log_min=None): QtCore.QObject.__init__(self) self.text_item = None self.name = name self.log = logging.getLogger(__name__ + '.' + name) self.units = units self.config = { 'name': name, 'y-axis': { 'limit': y_limit, 'log_min': y_log_min, }, 'show_min_max': 'lines', 'decimate_min_max': 1, 'trace_width': 1, } self._is_min_max_active = False # when zoomed out enough to display min/max self._y_pan = None self.vb = SignalViewBox(name=self.name) if y_limit is not None: y_min, y_max = y_limit self.vb.setLimits(yMin=y_min, yMax=y_max) self.vb.setYRange(y_min, y_max) self.y_axis = YAxis(name, log_enable=y_log_min is not None) self.y_axis.linkToView(self.vb) self.y_axis.setGrid(128) self._most_recent_data = None if name is not None: self.y_axis.setLabel(text=name, units=units) if units is not None: self.text_item = SignalStatistics(units=units) self._pen_min_max = pg.mkPen(color=(255, 64, 64), width=CURVE_WIDTH) self._brush_min_max = pg.mkBrush(color=(255, 64, 64, 80)) self._pen_mean = pg.mkPen(color=(255, 255, 64), width=CURVE_WIDTH) self.curve_mean = pg.PlotDataItem(pen=self._pen_mean) self.curve_max = pg.PlotDataItem(pen=self._pen_min_max) self.curve_min = pg.PlotDataItem(pen=self._pen_min_max) self.curve_range = pg.FillBetweenItem(self.curve_min, self.curve_max, brush=self._brush_min_max) self.vb.addItem(self.curve_range) self.vb.addItem(self.curve_max) self.vb.addItem(self.curve_min) self.vb.addItem(self.curve_mean) self.curve_max.hide() self.curve_min.hide() self.curve_range.hide() self.y_axis.sigConfigEvent.connect(self.y_axis_config_update) self.y_axis.sigWheelZoomYEvent.connect(self.on_wheelZoomY) self.y_axis.sigPanYEvent.connect(self.on_panY) self.y_axis.sigHideRequestEvent.connect( lambda name: self.sigHideRequestEvent.emit(name))
def addSigmaPlots(self, plt1, plt2): self.percent_low = plt1 self.percent_high = plt2 self.pfill = pg.FillBetweenItem(self.percent_high, self.percent_low, brush=(50, 50, 200, 50)) self.addItem(self.percent_low) self.addItem(self.percent_high) self.addItem(self.pfill)
def add_fill_between_plot(self, x, curve_1, curve_2, brush=(150, 150, 150, 100)): c_1 = self.win.plot(x=x, y=curve_1, pen=(0,0,0,0)) c_2 = self.win.plot(x=x, y=curve_2, pen=(0,0,0,0)) self.plots.append(c_1) self.plots.append(c_2) self.win.legend.addItem(c_1, '') self.win.legend.addItem(c_2, '') self.fbi = pg.FillBetweenItem(c_1, c_2, brush) self.win.addItem(self.fbi)
def plot_hypnogram(self): use_data = self.dataloader.PRED sleep_level = ['W', 'N1', 'N2', 'N3', 'REM'] calib = self.status['calib'] brush = pg.mkBrush(pg.hsvColor(0.6, 1, 0.3, 0.3)) lin_space = np.array( (np.arange(self.dataloader.PRED.shape[0]), np.arange(self.dataloader.PRED.shape[0])+1)) lin_space = lin_space.transpose().reshape(-1) # label_temp = np.array((self.dataloader.LABEL, self.dataloader.LABEL)) # label_temp = label_temp.transpose().reshape(-1) pred_temp = np.array((use_data, use_data)) pred_temp = pred_temp.transpose().reshape(-1) hypno_temp = np.array((self.user_annotation_record, self.user_annotation_record)) hypno_temp = hypno_temp.transpose().reshape(-1) ticks = [[(v, '{}'.format( self.time_format([23, 0, 0 + int(v*30)]))) for v in (np.arange( self.dataloader.PRED.shape[0])[0::50])]] y_ticks = [[(v, '{}'.format( sleep_level[v])) for v in np.arange(0, 5)]] y_ticks[0].append((-1, 'Not scored')) self.hypnogram_ax.clear() self.hypnogram_ax.setBackground('w') self.hypnogram_ax.setYRange(-1, 5) self.hypnogram_ax.setXRange(0, self.dataloader.PRED.shape[0]) self.hypnogram_ax.plot(lin_space, pred_temp, pen=pg.mkPen(color='b', width=POINTFIVE)) self.hypnogram_ax.plot(lin_space, hypno_temp, pen=pg.mkPen(color='r', width=POINTFIVE)) # self.hypnogram_ax.plot(lin_space, label_temp, # pen=pg.mkPen(color='g', width=0.5)) stem1 = pg.PlotDataItem(x=np.ones(5)*(self.status['counter']), y=np.linspace(-1, 6, 5)) stem2 = pg.PlotDataItem(x=np.ones(5)*(self.status['counter'] + 1), y=np.linspace(-1, 6, 5)) fbtwn = pg.FillBetweenItem(stem1, stem2, brush=brush) self.hypnogram_ax.addItem(fbtwn) x_axis = self.hypnogram_ax.getAxis('bottom') y_axis = self.hypnogram_ax.getAxis('left') x_axis.setTicks(ticks) y_axis.setTicks(y_ticks) self.annotate.info_pred_label.setText('Annotate as {}'.format( sleep_level[int(self.dataloader.PRED[self.status['counter']])])) self.annotate.reannotate_label.setText('Reannotate') self.hypnogram_ax.setTitle( 'Model Prediction: {}, Epoch: {}/{}' .format(sleep_level[int( self.dataloader.PRED[self.status['counter']])], self.status['counter'] + 1, len(self.dataloader.PRED) ) )
def __init__(self, xlabel, ylabel): self.fig = pg.PlotWidget(background='w') self.fig.setMouseEnabled(x=False, y=False) self.fig.setLabel('bottom', xlabel) self.fig.setLabel('left', ylabel) self.plot = pg.PlotCurveItem() self.plot_lb = pg.PlotCurveItem() self.plot_ub = pg.PlotCurveItem() self.plot_fill = pg.FillBetweenItem() self.fig.addItem(self.plot) self.fig.addItem(self.plot_fill)
def add_fill_curve(self, x, ylow, yhigh, pen): phigh = pg.PlotCurveItem(x, yhigh, pen=pen) plow = pg.PlotCurveItem(x, ylow, pen=pen) color = pen.color() color.setAlphaF(0.2) cc = pg.mkBrush(color) pfill = pg.FillBetweenItem(plow, phigh, brush=cc) pfill.setZValue(10) self.curves_cont.add_curve(pfill) # for zoom to work correctly self.curves_plotted.append((x, np.array([ylow, yhigh])))
def fill(self, curvenum1, curvenum2, brush=(50, 0, 0, 50)): for i in range(max(curvenum1, curvenum2)): try: self.curves[i] except: self.curves[i] = self.plot.plot( **self.styles[min(i, len(self.styles) - 1)]) fill = pg.FillBetweenItem(self.curves[curvenum1], self.curves[curvenum2], brush) self.plot.addItem(fill)
def prepare_widget(self, widget): super(ThresholdBlinkFeedbackProtocolWidgetPainter, self).prepare_widget(widget) self.p1 = widget.plot([-10, 10], [10, 10], pen=pg.mkPen(77, 144, 254)).curve self.p2 = widget.plot([-10, 10], [-10, -10], pen=pg.mkPen(77, 144, 254)).curve self.fill = pg.FillBetweenItem(self.p1, self.p2, brush=(255, 255, 255, 25)) widget.addItem(self.fill)
def addWindTrace(self, waveItem, plotItem): 'Add a fixed time winow for each trace' sacdh = waveItem.sacdh t0, t1 = tuple(np.array(sacdh.twindow) - sacdh.reftime) yy = [sacdh.datbase - 0.5, sacdh.datbase + 0.5] c0 = plotItem.plot([t0, t0], yy) c1 = plotItem.plot([t1, t1], yy) ff = pg.FillBetweenItem(c0, c1, brush=self.opts.colortwfill) plotItem.addItem(ff) waveItem.twinFill = ff waveItem.twinCurves = [c0, c1]
def setup_plot_signal_noise(self, hist_len): '''Plots the signal and the noise as a function of the experimental time.''' self.ax_signal_noise.setLabel('left', text='Amplitude') self.ax_signal_noise.setLabel('bottom', text='Measurement time (s)') self.ax_signal_noise.setTitle('Correlation signal and noise') self.ax_signal_noise.setLimits(yMin=0) self.ax_signal_noise.addLegend() # self.ax_signal_noise.ticklabel_format(style='sci', axis='x', useMathText=True) self.signal_std_arr = np.array([]) # signal amplitude self.plot_signal_amp = self.ax_signal_noise.plot( [0], [0], pen=pg.mkPen(FIT_COLOR), symbolPen=None, symbol='o', symbolSize=5, symbolBrush=pg.mkBrush(FIT_COLOR), name='Signal amplitude \u00B1 2σ') self.plot_signal_amp.setData([], []) # confidence bands upper = pg.PlotDataItem([0], [0]) lower = pg.PlotDataItem([0], [0]) self.plot_signal_err = pg.FillBetweenItem( upper, lower, brush=pg.mkBrush(FIT_ERROR_COLOR)) self.ax_signal_noise.addItem(self.plot_signal_err) # last signal amplitude self.plot_signal_line = pg.InfiniteLine(pos=0, angle=0, movable=False, pen=pg.mkPen(FIT_COLOR, width=2), name='Last signal amplitude') self.ax_signal_noise.addItem(self.plot_signal_line) # noise amplitude self.plot_noise_amp = self.ax_signal_noise.plot( [0], [0], pen=pg.mkPen(NOISE_COLOR), symbolPen=None, symbol='o', symbolSize=5, symbolBrush=pg.mkBrush(NOISE_COLOR), name='Noise amplitude and fit to t<sup>-\u00BD</sup>') self.plot_noise_amp.setData([], []) # noise fit to t^(-1/2) self.plot_noise_fit = self.ax_signal_noise.plot( [0], [0], pen=pg.mkPen(NOISE_COLOR)) self.plot_noise_fit.setData([], [])
def refresh(self): self.plot.clear() silhouette_values = self.controller.spike_silhouette if silhouette_values is None: return if silhouette_values.shape != self.controller.spike_label.shape: return silhouette_avg = np.mean(silhouette_values) silhouette_by_labels = {} labels = self.controller.spike_label labels_list = np.unique(labels) for k in labels_list: v = silhouette_values[k==labels] v.sort() silhouette_by_labels[k] = v self.vline = pg.InfiniteLine(pos=silhouette_avg, angle = 90, movable = False, pen = '#FF0000') self.plot.addItem(self.vline) y_lower = 10 cluster_visible = self.controller.cluster_visible visibles = [c for c, v in self.controller.cluster_visible.items() if v and c>=0] for k in visibles: if k not in silhouette_by_labels: continue v = silhouette_by_labels[k] color = self.controller.qcolors[k] color2 = QT.QColor(color) color2.setAlpha(self.alpha) y_upper = y_lower + v.size y_vect = np.arange(y_lower, y_upper) curve1 = pg.PlotCurveItem(np.zeros(v.size), y_vect, pen=color) curve2 = pg.PlotCurveItem(v, y_vect, pen=color) self.plot.addItem(curve1) self.plot.addItem(curve2) fill = pg.FillBetweenItem(curve1=curve1, curve2=curve2, brush=color2) self.plot.addItem(fill) txt = pg.TextItem( text='{}'.format(k), color='#FFFFFF', anchor=(0, 0.5), border=None)#, fill=pg.mkColor((128,128,128, 180))) self.plot.addItem(txt) txt.setPos(0, (y_upper+y_lower)/2.) y_lower = y_upper + 10 self.plot.setXRange(-.5, 1.) self.plot.setYRange(0,y_lower)
def plotSigma(l = 'b_lambda',err = 'b_cube_err', index = None): color = pg.mkBrush(0.3) if index is None:index = np.arange(self.data[l].shape[0]) try: p1 = pg.PlotDataItem(self.data[l][index],-1 * self.data[err][index,int(self.y),int(self.x)]) p2 = pg.PlotDataItem(self.data[l][index], self.data[err][index,int(self.y),int(self.x)]) p1.curve.path , p2.curve.path = p1.curve.generatePath(*p1.curve.getData()), p2.curve.generatePath(*p2.curve.getData()) item = pg.FillBetweenItem(p1, p2, brush = color) except: item = pg.PlotCurveItem(self.data[l][index],self.data[l][index]*0) # return trash item.setVisible(False) return item
def traces(data, tt=None, xx=None, color='k', sf=0.15, verbose=False, shade=False): """Plot large seismic dataset in real time using pyqtgraph """ # Input check data, tt, xx, ts = wiggle_input_check(data, tt, xx, sf, verbose) Ntr = data.shape[1] pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') pg.setConfigOptions(antialias=True) # Enable antialiasing p = pg.plot() for ntr in range(Ntr): trace = data[:, ntr] offset = xx[ntr] if shade: # Insert zeros trace_zi, tt_zi = insert_zeros(trace, tt) # Seperate top and bottom line trace_top = np.array( [i + offset if i >= 0 else None for i in trace_zi], dtype='float64') trace_line = np.array( [offset if i >= 0 else None for i in trace_zi], dtype='float64') trace_bot = np.array( [i + offset if i <= 0 else None for i in trace_zi], dtype='float64') # Plot top and bottom top = p.plot(x=trace_top, y=tt_zi, pen=color) bot = p.plot(x=trace_line, y=tt_zi, pen=color) p.plot(x=trace_bot, y=tt_zi, pen=color) fill = pg.FillBetweenItem(bot, top, brush=color) p.addItem(fill) else: p.plot(x=trace + offset, y=tt, pen=color) p.showGrid(x=True, y=True, alpha=0.3) p.invertY(True) p.setRange(yRange=[np.min(tt), np.max(tt)], padding=0) return p