def mouseClickEvent(self,event): if self.click_deferred is not None: self.click_deferred.callback(self.getViewBox().mapSceneToView(event.scenePos()).x()) event.accept() self.click_deferred = None else: PlotItem.mouseClickEvent(self,event)
class PixelSpace(ImageView): def __init__(self, *args, **kwargs): # Add axes self.axesItem = PlotItem() self.axesItem.axes["left"]["item"].setZValue(10) self.axesItem.axes["top"]["item"].setZValue(10) if "view" not in kwargs: kwargs["view"] = self.axesItem self._transform = QTransform() self._raw_image = None super(PixelSpace, self).__init__(*args, **kwargs) self.imageItem.sigImageChanged.connect(self.updateAxes) def transform(self, img=None): # Build Quads shape = img.shape a = [(0, shape[-2] - 1), (shape[-1] - 1, shape[-2] - 1), (shape[-1] - 1, 0), (0, 0)] b = [(0, 1), (shape[-1] - 1, 1), (shape[-1] - 1, shape[-2]), (0, shape[-2])] quad1 = QPolygonF() quad2 = QPolygonF() for p, q in zip(a, b): quad1.append(QPointF(*p)) quad2.append(QPointF(*q)) transform = QTransform() QTransform.quadToQuad(quad1, quad2, transform) for item in self.view.items: if isinstance(item, ImageItem): item.setTransform(transform) self._transform = transform return img, transform def setImage(self, img, *args, **kwargs): if img is None: return if getattr(self, "displaymode", DisplayMode.raw) == DisplayMode.raw: self._raw_image = img if not kwargs.get("transform", None): img, transform = self.transform(img) self.updateAxes() super(PixelSpace, self).setImage(img, *args, transform=transform, **kwargs) else: super(PixelSpace, self).setImage(img, *args, **kwargs) def setTransform(self): self.setImage(self._raw_image) # this should loop back around to the respective transforms def updateAxes(self): self.axesItem.setLabel("bottom", "x (px)") # , units='s') self.axesItem.setLabel("left", "z (px)")
def createGraph(self, data, graph): plot = PlotItem() line = PlotCurveItem(x=asarray( [x for x in range(0, self.element.sections + 1)]), y=data, pxMode=True, symbolSize=5) plot.addItem(line) graph.addItem(plot, row=0, col=0)
def _PlotItem_addItem(self, item, *args, **kwargs): """replacement for `PlotItem.addItem` that Y2Axis will use to monkey-patch the original one """ PlotItem.addItem(self, item, *args, **kwargs) if hasattr(item, "setLogMode"): item.setLogMode( self.getAxis("bottom").logMode, self.getAxis("left").logMode)
def __init__(self, info: pylsl.StreamInfo, plt: pg.PlotItem): super().__init__(info) # calculate the size for our buffer, i.e. two times the displayed data bufsize = (2 * math.ceil(info.nominal_srate() * plot_duration), info.channel_count()) self.buffer = np.empty(bufsize, dtype=self.dtypes[info.channel_format()]) empty = np.array([]) # create one curve object for each channel/line that will handle displaying the data self.curves = [pg.PlotCurveItem(x=empty, y=empty, autoDownsample=True) for _ in range(self.channel_count)] for curve in self.curves: plt.addItem(curve)
def __init__(self, *args, plot_data=None, **kwargs): # Setup GUI self.plot_view = PlotItem() super(PyQtGraphPlot, self).__init__( *args, view=self.plot_view, **kwargs) self._setup() self.model = PyQtGraphPlotModel(plot_data) self.refresh_plot()
def __init__(self, header: NonDBHeader = None, field: str = 'primary', toolbar: QToolBar = None, *args, **kwargs): # Add axes self.axesItem = PlotItem() # self.axesItem.setLabel('bottom', u'q ()') # , units='s') # self.axesItem.setLabel('bottom', u'q ()') # , units='s') # self.axesItem.setLabel('left', u'q ()') self.axesItem.axes['left']['item'].setZValue(10) self.axesItem.axes['top']['item'].setZValue(10) if 'view' not in kwargs: kwargs['view'] = self.axesItem super(EFIViewerPlugin, self).__init__(**kwargs) self.axesItem.invertY(True) # Setup axes reset button self.resetAxesBtn = QPushButton('Reset Axes') sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth( self.resetAxesBtn.sizePolicy().hasHeightForWidth()) self.resetAxesBtn.setSizePolicy(sizePolicy) self.resetAxesBtn.setObjectName("resetAxes") self.ui.gridLayout.addWidget(self.resetAxesBtn, 2, 1, 1, 1) self.resetAxesBtn.clicked.connect(self.autoRange) # Setup LUT reset button self.resetLUTBtn = QPushButton('Reset LUT') sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth( self.resetLUTBtn.sizePolicy().hasHeightForWidth()) # self.resetLUTBtn.setSizePolicy(sizePolicy) # self.resetLUTBtn.setObjectName("resetLUTBtn") self.ui.gridLayout.addWidget(self.resetLUTBtn, 3, 1, 1, 1) self.resetLUTBtn.clicked.connect(self.autoLevels) # Hide ROI button and rearrange # self.ui.roiBtn.setParent(None) # self.ui.gridLayout.addWidget(self.ui.menuBtn, 1, 1, 1, 1) # self.ui.gridLayout.addWidget(self.ui.graphicsView, 0, 0, 3, 1) # Setup coordinates label # self.coordinatesLbl = QLabel('--COORDINATES WILL GO HERE--') # self.ui.gridLayout.addWidget(self.coordinatesLbl, 3, 0, 1, 1, alignment=Qt.AlignHCenter) # Set header if header: self.setHeader(header, field)
def __init__(self, *args, **kwargs): # Add axes self.axesItem = PlotItem() self.axesItem.axes["left"]["item"].setZValue(10) self.axesItem.axes["top"]["item"].setZValue(10) if "view" not in kwargs: kwargs["view"] = self.axesItem super(XArrayView, self).__init__(*args, **kwargs) self.view.invertY(False)
def __init__(self, *args, **kwargs): # Add axes self.axesItem = PlotItem() self.axesItem.axes["left"]["item"].setZValue(10) self.axesItem.axes["top"]["item"].setZValue(10) if "view" not in kwargs: kwargs["view"] = self.axesItem self._transform = QTransform() super(PixelSpace, self).__init__(*args, **kwargs) self.imageItem.sigImageChanged.connect(self.updateAxes)
class PlotDepictor(Depictor): def __init__(self, datablock): super().__init__(datablock) self.plot = PlotItem() self.plot.addLegend() def add_line(self, y, name, x=None, color='w'): if x is None: x = range(len(y)) self.plot.plot(x, y, name=name, pen=color) def purge(self): self.plot = PlotItem()
def __init__(self, main_widget, histogram=True, crop_selector=False): super().__init__() self.main_widget = main_widget # self.setMinimumWidth(600) # self.setMinimumHeight(300) # self.setStyleSheet("ImageViewModule {margin:5px; border:1px solid rgb(50, 65, " # "75);} ") self.setStyleSheet("ImageViewModule {margin:0px; border:0px solid rgb(50, 65, " "75); padding: 0px;} ") self.layout = QVBoxLayout() self.layout.setContentsMargins(0, 0, 0, 0) # self.layout.setAlignment(Qt.AlignHCenter) self.image_label = QLabel() self.layout.addWidget(self.image_label) self.setLayout(self.layout) # self.already_loaded = True # self.no_image_message = QPushButton("Please open a dataset first") # self.no_image_message.clicked.connect(main_widget.open_file_dialog) # self.no_image_message.setStyleSheet("QPushButton {font-size:80;}") self.image_view = ImageView(view=PlotItem()) self.image_view.keyPressEvent = self.keyPressEvent self.image_view.ui.layoutWidget.setContentsMargins(0, 0, 0, 0) # self.image_view.ui.roiBtn.hide() self.image_view.ui.menuBtn.hide() if not histogram: self.image_view.ui.histogram.hide() if not crop_selector: self.image_view.ui.roiBtn.hide() # self.image_view.getRoiPlot().hide() self.image_item = self.image_view.getImageItem() self.layout.addWidget(self.image_view)
def __init__(self, parent=None, image_channel=None, width_channel=None): """Initialize widget.""" # Set the default colormap. self._colormap = PyDMColorMap.Inferno self._cm_colors = None self._imagechannel = None self._widthchannel = None self.image_waveform = np.zeros(0) self._image_width = 0 self._normalize_data = False self._auto_downsample = True self._show_axes = False # Set default reading order of numpy array data to Fortranlike. self._reading_order = ReadingOrder.Fortranlike self._redraw_rate = 30 # Set color map limits. self.cm_min = 0.0 self.cm_max = 255.0 plot_item = PlotItem() ImageView.__init__(self, parent, view=plot_item) PyDMWidget.__init__(self) self._channels = [None, None] self.thread = None self.axes = dict({'t': None, "x": 0, "y": 1, "c": None}) self.showAxes = self._show_axes self.imageItem.setOpts(axisOrder="row-major") # Hide some itens of the widget. self.ui.histogram.hide() self.getImageItem().sigImageChanged.disconnect( self.ui.histogram.imageChanged) self.ui.roiBtn.hide() self.ui.menuBtn.hide() # Make a right-click menu for changing the color map. self.cm_group = QActionGroup(self) self.cmap_for_action = {} for cm in self.color_maps: action = self.cm_group.addAction(cmap_names[cm]) action.setCheckable(True) self.cmap_for_action[action] = cm self.colorMap = self._colormap # Setup the redraw timer. self.needs_redraw = False self.redraw_timer = QTimer(self) self.redraw_timer.timeout.connect(self.redrawImage) self.maxRedrawRate = self._redraw_rate self.newImageSignal = self.getImageItem().sigImageChanged # Set live channels if requested on initialization if image_channel: self.imageChannel = image_channel or '' if width_channel: self.widthChannel = width_channel or ''
def create_plots(self): self.plotDict = { "plotItem": PlotItem(), "plotDataItem": None, "displayed": 1 } self.pyqtgraphWidget.addItem(self.plotDict["plotItem"]) self.plotDict["plotDataItem"] = self.plotDict["plotItem"].plot()
def __init__(self, layout, range, *args, **kwargs): self.plot_view = PlotItem(lockAspect=1) super(ImagePlot, self).__init__(*args, view=self.plot_view, **kwargs) layout.insertWidget(0, self) self.setup(range) self.show()
def lin_hover_handler(self, i: int, lin: pg.PlotItem, evt: tuple): if lin.sceneBoundingRect().contains(evt[0]): self.mouse_panel = 'lin_' + self.index_to_coord[i] mousepnt = lin.vb.mapSceneToView(evt[0]) self.mouse_pos = mousepnt self.status_bar = "{0:#.5g}, {1:#.5g}".format(mousepnt.x(), mousepnt.y()) self.mouse_hover.emit(self.status_bar) if self.shift_down: self.set_crosshair_to_mouse()
def __init__(self, dbeta, rh): self.dbeta = dbeta self.p4main = glo_var.MyPW(x="\u03b2", y1="J", y2="\u27e8\u2374\u27e9", set_range=self.set_range) # self.p4main._rescale = self.set_range self.p4 = self.p4main.plotItem self.viewbox = self.p4.getViewBox() # self.viewbox.setBackgroundColor('w') self.item = self.p4 self.p4main.tempplotitem = PlotItem() self.p4_2 = self.p4main.tempplotitem.vb self.p4.setLabel('left', "J", **glo_var.labelstyle) self.p4.setLabel('bottom', "\u03b2", **glo_var.labelstyle) self.p4.setLabel('right', "\u27e8\u2374\u27e9", **glo_var.labelstyle) # self.p4main.set_range = self.set_range self.rh = rh self.rho_dash = mkPen(color=(16, 52, 166), width=glo_var.line_width, style=QtCore.Qt.DashLine) self.dash = mkPen('r', width=glo_var.line_width, style=QtCore.Qt.DashLine) self.jpen = mkPen('k', width=glo_var.line_width) self.beta_pen = mkPen('k', width=glo_var.line_width) self.p4.addLegend = glo_var.myaddLegend self.p4.addLegend(self.p4, offset=(20, 20)) self.p4.showAxis('right') self.p4.scene().addItem(self.p4_2) self.p4.getAxis('right').linkToView(self.p4_2) self.p4_2.setXLink(self.p4) self.p4_2.setBackgroundColor('w') self.p4main.coordinate_label = QtGui.QLabel() self.frame = glo_var.setframe( self.p4main, width=1, coordinate_label=self.p4main.coordinate_label) self.dbeta.addWidget(self.frame) self.viewbox.setLimits(xMin=0, yMin=0, xMax=1, yMax=1) self.p4_2.setLimits(xMin=0, yMin=0, xMax=1, yMax=1) self.p4.vb.sigResized.connect(self.updateview) self.update() self.legend()
def __init__(self, layout, x, y, *args, **kwargs): self.plot_view = PlotItem() super(SurfacePlot, self).__init__(*args, **kwargs) layout.insertWidget(0, self) self.image = None self.setup(x, y) self.show()
def __init__(self,parent,scan): # name of independent variable input = scan[INPUT] x_label = input.get(NAME,'input') x_units = input.get(UNITS,'arb') # name of dependent variable output = scan[OUTPUT] if type(output) is dict: y_label = output.get(NAME,'output') y_units = output.get(UNITS,'arb') else: y_label = 'output' y_units = 'arb' # scan title title = scan.get( NAME, '%s vs. %s' % (y_label,x_label) ) labels = { 'bottom':'%s (%s)' % (x_label,x_units), 'left':'%s (%s)' % (y_label,y_units) } # initialize pyqtgraph plot item with title and axis labels PlotItem.__init__( self, title = title, labels = labels ) # are we setting input to optimal value of scan result? self.optimizing = scan.get(OPTIMIZE,False) # if we have multiple outputs and are optimizing, which output to optimize? self.checking_optimize = scan.get(CHECK_OPTIMIZE,False) self.click_deferred = None self.optimize_axis = scan.get(OPTIMIZE_AXIS,0) # are we saving scan data to datavault? self.saving = scan.get(SAVE,False) # are we returning to input's original position after scan? self.returning = scan.get(RETURN,False) self.scan = scan self.__parent = parent
def __init__(self, model, video_model=None, parent=None, colormap="inferno"): """ Sets the datamodel and optionally a videomodel that is used to print a time indicator according to its current frameself. Args: model: DataModel wrapping either 1d or 2d data video_model: VideoModel wrapping a video file parent: Parent QtWidget colormap: String describing matplotlib colormap """ self.view = PlotItem() super().__init__(view=self.view) self.model = model self.video_model = video_model self.print_indicator = False self.indicator = None # Get a colormap colormap = plt.cm.get_cmap( colormap) # cm.get_cmap("CMRmap")nipy_spectral colormap._init() self.lut = (colormap._lut * 255).view( np.ndarray ) # Convert matplotlib colormap from 0-1 to 0 -255 for Qt self.ui.histogram.hide() self.ui.roiBtn.hide() self.ui.menuBtn.hide() initial_data = self.model.get_data() if not isinstance(initial_data, type(None)): #Draw imagedata if possible try: self.print_data(initial_data) except: #It might be that the model contains data that is not displayable e.g. 1d pass
def create_plots(self): self.allPlotsDict["plot"] = {"plotItem": PlotItem(), "displayed": 1} #self.allPlotsDict["plot"]["plotItem"].setXRange(0, 30000) red = mkColor('r') blue = mkColor('b') green = mkColor('g') dataPlotItem = self.allPlotsDict["plot"]["plotItem"].plot(pen=mkPen(red, width=2)) self.allPlotsDict["plot"]["voltage"] = dataPlotItem dataPlotItem = self.allPlotsDict["plot"]["plotItem"].plot(pen=mkPen(blue, width=2)) self.allPlotsDict["plot"]["current"] = dataPlotItem dataPlotItem = self.allPlotsDict["plot"]["plotItem"].plot(pen=mkPen(green, width=2)) self.allPlotsDict["plot"]["temperature"] = dataPlotItem self.pyqtgraphWidget.addItem(self.allPlotsDict["plot"]["plotItem"])
def create_plots(self): for indicator in Person().indicators: self.allPlotsDict[indicator] = { "plotItem": PlotItem(), "displayed": 0 } for indicator in Person().indicators: self.allPlotsDict[indicator]["plotDataItem"] = {} for ageGroup in Person().ageGroupsList: dataPlotItem = self.allPlotsDict[indicator]["plotItem"].plot() self.allPlotsDict[indicator]["plotDataItem"][ ageGroup] = dataPlotItem # self.allPlotsDict[indicator]["plotDataItem"][ageGroup].setDownsampling() self.allPlotsDict[indicator]["plotItem"].setTitle(indicator) print(self.allPlotsDict)
def __init__(self): super().__init__() # settings self.setBackground("#fff") self.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken) self.setAntialiasing(True) # create custom view box view_box = ViewBox() view_box.setMouseEnabled(False, False) view_box.setLimits(xMin=0, yMin=0, minXRange=10, minYRange=100) view_box.setRange(xRange=(0, 400), yRange=(0, 5000)) view_box.enableAutoRange() # create natural axis items self.x_axis = NaturalAxis("bottom") self.x_axis.setLabel(QApplication.translate("NaturalPlotView", "Fence length"), "m") self.y_axis = NaturalAxis("left") self.y_axis.setLabel(QApplication.translate("NaturalPlotView", "Number of plants")) # create fence information text self.fenceItem = TextItem(border=pyqtgraph.mkPen(width=2, color="#555"), fill=pyqtgraph.mkBrush((255, 255, 255, 200))) # create tube information text self.tubeItem = TextItem(border=pyqtgraph.mkPen(width=2, color="#555"), fill=pyqtgraph.mkBrush((255, 255, 255, 200)), anchor=(1,1)) # create plot item with custom view box and natural axis items self.plotItem = PlotItem(viewBox=view_box, axisItems={"bottom" : self.x_axis, "left" : self.y_axis}, enableMenu=False) self.plotItem.setContentsMargins(5, 5, 12, 5) self.plotItem.hideButtons() self.plotItem.hide() self.setCentralWidget(self.plotItem) # connect actions view_box.sigResized.connect(self.updateTubeLegendPosition) # translate the plot item self.retranslateUi()
def __init__(self, axes: PlotItem, direction: Direction, range_type: Type[_Range], scale_type: Type[_Scale], *args, **kwargs): self._axes: PlotItem = axes self._raw: AxisItem = axes.getAxis(self._axis_name()) self._label: Axis._Label = Axis._Label(self._raw) self._scale: Axis._Scale = scale_type(self._axes, self._raw) self._range: Axis._Range = range_type(self._axes, self._raw) self._scale_line: Axis._ScaleLine = Axis._ScaleLine(self._raw) # self._ticks: Axis._Ticks = Axis._Ticks(self._raw, alt=(np.array([]), np.array([]))) self._ticks: np.ndarray = np.array([]) self._tick_labels: np.ndarray = np.array([]) self._minor_ticks: np.ndarray = np.array([]) self._minor_tick_labels: np.ndarray = np.array([]) self._tick_raw: List[Tuple[float, Any]] = [] super(Axis, self).__init__(direction, *args, **kwargs)
def __init__(self, plot: pg.PlotItem, parent: QWidget): super().__init__(parent) self.setWindowTitle('Plot detail') # Get all items in the plot gItems = plot.listDataItems() # Create a new plot and set its position in the scatterplot matrix (col and row parameters) nPlot = pg.PlotItem() nPlot.addLegend(pen=pg.mkPen(.8, width=1)) nPlot.row = plot.row nPlot.col = plot.col # Move all the items from the original plot to the new plot for it in gItems: nPlot.addItem(it) nPlot.setLabel(axis='left', text=plot.yName) nPlot.setLabel(axis='bottom', text=plot.xName) # Make a plot widget to hold the PlotItem self.plotWidget = pg.PlotWidget(parent=self, plotItem=nPlot) self.plotWidget.setCentralItem(nPlot) self.plotItem = nPlot # Show the plot in a new window self.setWindowFlag(Qt.Window) # Layout is needed QHBoxLayout(self).addWidget(self.plotWidget)
class SweepDataPlot(GraphicsView): GREEN = [0, 204, 153] BLUE = [100, 171, 246] RED = [221, 61, 53] PURPLE = [175, 122, 197] ASH = [52, 73, 94] GRAY = [178, 186, 187] COLORS = [BLUE, RED, GREEN, PURPLE, ASH, GRAY] if sys.platform == 'darwin': LW = 3 else: LW = 1.5 def __init__(self): GraphicsView.__init__(self) # create layout self.layout = pg.GraphicsLayout() self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(-1.) self.setBackground(None) self.setCentralItem(self.layout) # create axes and apply formatting axisItems = dict() for pos in ['bottom', 'left', 'top', 'right']: axisItems[pos] = AxisItem(orientation=pos, maxTickLength=-7) self.p = PlotItem(axisItems=axisItems) self.setTitle('Sweep data', fontScaling=1.3, color='k') self.layout.addItem(self.p) self.p.vb.setBackgroundColor('w') self.p.setContentsMargins(10, 10, 10, 10) for pos in ['bottom', 'left', 'top', 'right']: ax = self.p.getAxis(pos) ax.setZValue(0) # draw on top of patch ax.setVisible(True) # make all axes visible ax.setPen(width=self.LW * 2 / 3, color=0.5) # grey spines and ticks try: ax.setTextPen('k') # black text except AttributeError: pass ax.setStyle(autoExpandTextSpace=True, tickTextOffset=4) self.p.getAxis('top').setTicks([]) self.p.getAxis('top').setHeight(0) self.p.getAxis('right').setTicks([]) self.x_axis = self.p.getAxis('bottom') self.y_axis = self.p.getAxis('left') self.x_axis.setLabel('Voltage', units='V', color='k', size='12pt') self.y_axis.setLabel('Current', units='A', color='k', size='12pt') self.y_axis.setStyle(tickTextWidth=35) # set auto range and mouse panning / zooming self.p.enableAutoRange(x=True, y=True) self.p.setLimits(xMin=-1e20, xMax=1e20, yMin=-1e20, yMax=1e20) def suggestPadding(axis): length = self.p.vb.width() if axis == 0 else self.p.vb.height() if length > 0: if axis == 0: padding = 0 else: padding = np.clip(1. / (length**0.5), 0.02, 0.1) else: padding = 0.02 return padding self.p.vb.suggestPadding = suggestPadding # set default ranges to start self.p.setXRange(-10, 10) self.p.setYRange(-10, 10) # add legend self.legend = LegendItem(brush=fn.mkBrush(255, 255, 255, 150), labelTextColor='k', offset=(20, -20)) self.legend.setParentItem(self.p.vb) def clear(self): self.p.clear() # clear current plot self.legend.clear() # clear current legend def plot(self, sweep_data): self.clear() xdata = sweep_data.get_column(0) xdata_title = sweep_data.titles[0] ydata = sweep_data.values()[1:] # format plot according to sweep type unit = xdata_title.unit if xdata_title.has_unit() else 'a.u.' self.x_axis.setLabel(xdata_title.name, unit=unit) self.y_axis.setLabel('Current', unit='A') if sweep_data.params['sweep_type'] == 'transfer': self.setTitle('Transfer curve') self.p.setLogMode(x=False, y=True) self.legend.setOffset((20, -20)) # legend in bottom-left corner ydata = [np.abs(y) for y in ydata] elif sweep_data.params['sweep_type'] == 'output': self.setTitle('Output curve') self.p.setLogMode(x=False, y=False) self.legend.setOffset((-20, 20)) # legend in top-right corner ydata = [np.abs(y) for y in ydata] else: self.setTitle('Sweep curve') self.p.setLogMode(x=False, y=False) ydata = [np.abs(y) for y in ydata] # plot data self.lines = [] for y, c in zip(ydata, itertools.cycle(self.COLORS)): p = self.p.plot(xdata, y, pen=fn.mkPen(color=c, width=self.LW)) self.lines.append(p) # add legend for l, t in zip(self.lines, sweep_data.column_names[1:]): self.legend.addItem(l, str(t)) self.p.autoRange() def setTitle(self, text, fontScaling=None, color=None, font=None): # work around pyqtplot which forces the title to be HTML if text is None: self.p.setTitle(None) # clears title and hides title column else: self.p.setTitle( '') # makes title column visible, sets placeholder text self.p.titleLabel.item.setPlainText( text) # replace HTML with plain text if color is not None: color = fn.mkColor(color) self.p.titleLabel.item.setDefaultTextColor(color) if font is not None: self.p.titleLabel.item.setFont(font) if fontScaling is not None: font = self.p.titleLabel.item.font() defaultFontSize = QtWidgets.QLabel('test').font().pointSize() fontSize = round(defaultFontSize * fontScaling, 1) font.setPointSize(fontSize) self.p.titleLabel.item.setFont(font)
class InteractiveImagePlot(ImageView): """ Allows to draw 2d numpy array in an interactive plot using a colormap""" def __init__(self, model, video_model=None, parent=None, colormap="inferno"): """ Sets the datamodel and optionally a videomodel that is used to print a time indicator according to its current frameself. Args: model: DataModel wrapping either 1d or 2d data video_model: VideoModel wrapping a video file parent: Parent QtWidget colormap: String describing matplotlib colormap """ self.view = PlotItem() super().__init__(view=self.view) self.model = model self.video_model = video_model self.print_indicator = False self.indicator = None # Get a colormap colormap = plt.cm.get_cmap( colormap) # cm.get_cmap("CMRmap")nipy_spectral colormap._init() self.lut = (colormap._lut * 255).view( np.ndarray ) # Convert matplotlib colormap from 0-1 to 0 -255 for Qt self.ui.histogram.hide() self.ui.roiBtn.hide() self.ui.menuBtn.hide() initial_data = self.model.get_data() if not isinstance(initial_data, type(None)): #Draw imagedata if possible try: self.print_data(initial_data) except: #It might be that the model contains data that is not displayable e.g. 1d pass def print_data(self, data): """ Prints data to dataplot Args: data: 2d float.64 numpy arrays containing values between 0 and 1 """ self.print_indicator = True self.imagedata = data self.setImage(self.imagedata) self.indicator_min = -200 self.indicator_max = 200 if self.video_model != None: pos = int(self.video_model.get_pos(datatype="motion")) self.indicator = self.view.plot( [pos, pos], [self.indicator_min, self.indicator_max], pen=pyqtgraph.mkPen(color=pyqtgraph.hsvColor(2), width=1)) def update(self, pos): """ Updates indicator position Args: pos: Int describing the current position of the indicator """ if self.print_indicator and self.indicator and not self.video_model == None: C = pyqtgraph.hsvColor(1) pen = pyqtgraph.mkPen(color=C, width=1) pos = int( self.video_model.get_pos(datatype=self.model.get_datatype())) self.indicator.setData([pos, pos], [self.indicator_min, self.indicator_max]) def updateImage(self, autoHistogramRange=True): """ Updates the image, setting the colormap""" super().updateImage(autoHistogramRange=autoHistogramRange) self.getImageItem().setLookupTable(self.lut) def setImage(self, *args, **kwargs): """ Sets the image and adjusts the initial view/zoom in the plot""" super().setImage(*args, **kwargs) self.view.disableAutoRange(axis=0) self.view.enableAutoRange(axis=1)
def __init__(self, datablock): super().__init__(datablock) self.plot = PlotItem() self.plot.addLegend()
def purge(self): self.plot = PlotItem()
def __init__(self, Node): PlotItem.__init__(self) self.setMinimumSize(300, 300) NodeView.__init__(self, Node)
app = QtGui.QApplication([]) window = QMainWindow() holder = QWidget() holder_layout = QGridLayout() holder.setLayout(holder_layout) window.setCentralWidget(holder) # # Grid section # grid_widget = pg.GraphicsLayoutWidget() grid_viewBox1 = ViewBox(enableMenu=True) grid_viewBox1.setXRange(0, 5, padding=0) grid_viewBox1.setYRange(0, 2.5, padding=0) grid_subplot1 = PlotItem(viewBox=grid_viewBox1) grid_subplot1.showGrid(True, True, 0.2) grid_viewBox1.setParent(grid_subplot1) grid_widget.addItem(grid_subplot1, col=0, row=0) grid_viewBox2 = ViewBox(enableMenu=True) grid_viewBox2.setXRange(0, 5, padding=0) grid_viewBox2.setYRange(0, 2.5, padding=0) grid_subplot2 = PlotItem(viewBox=grid_viewBox2) grid_subplot2.showGrid(True, True, 0.2) grid_viewBox2.setParent(grid_subplot2) grid_widget.addItem(grid_subplot2, col=1, row=0) grid_viewBox3 = ViewBox(enableMenu=True) grid_viewBox3.setXRange(0, 5, padding=0) grid_viewBox3.setYRange(0, 2.5, padding=0)
def create_plots(self): self.plotDict["plotItem"] = PlotItem() # self.plotDict["plotDataItem"] = self.plotDict["plotItem"].plot() self.pyqtgraphWidget.addItem(self.plotDict["plotItem"]) self.plotDict["BarGraphItem"] = None
class NaturalPlotView(GraphicsView): """Creates a simple about dialog. The about dialog contains general information about the application and shows the copyright notice. That's why the class has no attributes or return values. """ def __init__(self): super().__init__() # settings self.setBackground("#fff") self.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken) self.setAntialiasing(True) # create custom view box view_box = ViewBox() view_box.setMouseEnabled(False, False) view_box.setLimits(xMin=0, yMin=0, minXRange=10, minYRange=100) view_box.setRange(xRange=(0, 400), yRange=(0, 5000)) view_box.enableAutoRange() # create natural axis items self.x_axis = NaturalAxis("bottom") self.x_axis.setLabel(QApplication.translate("NaturalPlotView", "Fence length"), "m") self.y_axis = NaturalAxis("left") self.y_axis.setLabel(QApplication.translate("NaturalPlotView", "Number of plants")) # create fence information text self.fenceItem = TextItem(border=pyqtgraph.mkPen(width=2, color="#555"), fill=pyqtgraph.mkBrush((255, 255, 255, 200))) # create tube information text self.tubeItem = TextItem(border=pyqtgraph.mkPen(width=2, color="#555"), fill=pyqtgraph.mkBrush((255, 255, 255, 200)), anchor=(1,1)) # create plot item with custom view box and natural axis items self.plotItem = PlotItem(viewBox=view_box, axisItems={"bottom" : self.x_axis, "left" : self.y_axis}, enableMenu=False) self.plotItem.setContentsMargins(5, 5, 12, 5) self.plotItem.hideButtons() self.plotItem.hide() self.setCentralWidget(self.plotItem) # connect actions view_box.sigResized.connect(self.updateTubeLegendPosition) # translate the plot item self.retranslateUi() def retranslateUi(self): # title label titleStyle = "color: #111; font-size: 15px; font-weight: bold" titleLabel = "<span style='{style}'>{title}</span>".format(style=titleStyle, title="Ergebnis: Funktion(en) der Kostengleichheit") self.plotItem.setTitle(titleLabel) # axis items #self.x_axis.setLabel(QApplication.translate("NaturalPlotView", "Fence length"), "m") #self.y_axis.setLabel(QApplication.translate("NaturalPlotView", "Number of plants")) # fence hint self.fenceItem.setHtml("<p style='margin: 0; color: #555'><b>" + QApplication.translate("NaturalPlotView", "Pfeil über Funktion(en):") + "</b> " + QApplication.translate("NaturalPlotView", "Zaun günstiger") + "</p>") # tube hint self.tubeItem.setHtml("<p style='margin: 0; color: #555'><b>" + QApplication.translate("NaturalPlotView", "Pfeil unter Funktion(en):") + "</b> " + QApplication.translate("NaturalPlotView", "Wuchshülle günstiger") + "</p>") def addPlotItem(self, item, *args, **kwargs): # first show the plot item if not self.plotItem.isVisible(): self.plotItem.show() self.plotItem.addItem(item, *args, **kwargs) def removePlotItem(self, item): self.plotItem.removeItem(item) #TODO: def clear(self): self.plotItem.hide() self.plotItem.clear() def showDescription(self): viewBox = self.plotItem.getViewBox() self.fenceItem.setPos(15, 10) self.fenceItem.setParentItem(viewBox) rect = viewBox.screenGeometry() self.tubeItem.setPos(rect.width() - 15, rect.height() - 10) self.tubeItem.setParentItem(viewBox) def updateTubeLegendPosition(self): rect = self.plotItem.getViewBox().screenGeometry() self.tubeItem.setPos(rect.width() - 15, rect.height() - 10) def export(self, gfxfile): exporter = TestImageExporter(self.plotItem) exporter.parameters()["width"] = 2007.0 # 17 cm / 300 DPI # export the graphics to the selected file exporter.export(gfxfile)
def __init__(self, header: NonDBHeader = None, field: str = 'primary', toolbar: QToolBar = None, *args, **kwargs): # Add q axes self.axesItem = PlotItem() self.axesItem.setLabel('bottom', u'q (Å⁻¹)') # , units='s') self.axesItem.setLabel('left', u'q (Å⁻¹)') self.axesItem.axes['left']['item'].setZValue(10) self.axesItem.axes['top']['item'].setZValue(10) if 'view' not in kwargs: kwargs['view'] = self.axesItem super(SAXSViewerPlugin, self).__init__(**kwargs) self.axesItem.invertY(False) # Setup axes reset button self.resetAxesBtn = QPushButton('Reset Axes') sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth( self.resetAxesBtn.sizePolicy().hasHeightForWidth()) self.resetAxesBtn.setSizePolicy(sizePolicy) self.resetAxesBtn.setObjectName("resetAxes") self.ui.gridLayout.addWidget(self.resetAxesBtn, 2, 1, 1, 1) self.resetAxesBtn.clicked.connect(self.autoRange) # Setup LUT reset button self.resetLUTBtn = QPushButton('Reset LUT') sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth( self.resetLUTBtn.sizePolicy().hasHeightForWidth()) # self.resetLUTBtn.setSizePolicy(sizePolicy) # self.resetLUTBtn.setObjectName("resetLUTBtn") self.ui.gridLayout.addWidget(self.resetLUTBtn, 3, 1, 1, 1) self.resetLUTBtn.clicked.connect(self.autoLevels) # Hide ROI button and rearrange self.ui.roiBtn.setParent(None) self.ui.gridLayout.addWidget(self.ui.menuBtn, 1, 1, 1, 1) self.ui.gridLayout.addWidget(self.ui.graphicsView, 0, 0, 3, 1) # Setup coordinates label self.coordinatesLbl = QLabel('--COORDINATES WILL GO HERE--') self.ui.gridLayout.addWidget(self.coordinatesLbl, 3, 0, 1, 1, alignment=Qt.AlignHCenter) # Setup mask layer self.maskimage = pg.ImageItem(opacity=.25) self.view.addItem(self.maskimage) # Setup calibration layer self.calibrantimage = pg.ImageItem(opacity=.25) self.view.addItem(self.calibrantimage) # Empty ROI for later use self.maskROI = pg.PolyLineROI([], closed=True, movable=False, pen=pg.mkPen(color='r', width=2)) self.maskROI.handlePen = pg.mkPen(color='r', width=2) self.maskROI.handleSize = 10 self.view.addItem(self.maskROI) # Connect toolbar handlers self.toolbar = toolbar if self.toolbar: self.toolbar.modegroup.triggered.connect(self.redraw) # Setup results cache self.results = [] # Set header if header: self.setHeader(header, field)
def __init__(self): GraphicsView.__init__(self) # create layout self.layout = pg.GraphicsLayout() self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(-1.) self.setBackground(None) self.setCentralItem(self.layout) # create axes and apply formatting axisItems = dict() for pos in ['bottom', 'left', 'top', 'right']: axisItems[pos] = AxisItem(orientation=pos, maxTickLength=-7) self.p = PlotItem(axisItems=axisItems) self.setTitle('Sweep data', fontScaling=1.3, color='k') self.layout.addItem(self.p) self.p.vb.setBackgroundColor('w') self.p.setContentsMargins(10, 10, 10, 10) for pos in ['bottom', 'left', 'top', 'right']: ax = self.p.getAxis(pos) ax.setZValue(0) # draw on top of patch ax.setVisible(True) # make all axes visible ax.setPen(width=self.LW * 2 / 3, color=0.5) # grey spines and ticks try: ax.setTextPen('k') # black text except AttributeError: pass ax.setStyle(autoExpandTextSpace=True, tickTextOffset=4) self.p.getAxis('top').setTicks([]) self.p.getAxis('top').setHeight(0) self.p.getAxis('right').setTicks([]) self.x_axis = self.p.getAxis('bottom') self.y_axis = self.p.getAxis('left') self.x_axis.setLabel('Voltage', units='V', color='k', size='12pt') self.y_axis.setLabel('Current', units='A', color='k', size='12pt') self.y_axis.setStyle(tickTextWidth=35) # set auto range and mouse panning / zooming self.p.enableAutoRange(x=True, y=True) self.p.setLimits(xMin=-1e20, xMax=1e20, yMin=-1e20, yMax=1e20) def suggestPadding(axis): length = self.p.vb.width() if axis == 0 else self.p.vb.height() if length > 0: if axis == 0: padding = 0 else: padding = np.clip(1. / (length**0.5), 0.02, 0.1) else: padding = 0.02 return padding self.p.vb.suggestPadding = suggestPadding # set default ranges to start self.p.setXRange(-10, 10) self.p.setYRange(-10, 10) # add legend self.legend = LegendItem(brush=fn.mkBrush(255, 255, 255, 150), labelTextColor='k', offset=(20, -20)) self.legend.setParentItem(self.p.vb)
class XArrayView(ImageView): def __init__(self, *args, **kwargs): # Add axes self.axesItem = PlotItem() self.axesItem.axes["left"]["item"].setZValue(10) self.axesItem.axes["top"]["item"].setZValue(10) if "view" not in kwargs: kwargs["view"] = self.axesItem super(XArrayView, self).__init__(*args, **kwargs) self.view.invertY(False) def setImage(self, img, **kwargs): if hasattr(img, 'coords'): if 'transform' not in kwargs: xvals = img.coords[img.dims[-2]] yvals = img.coords[img.dims[-1]] xmin = float(xvals.min()) xmax = float(xvals.max()) ymin = float(yvals.min()) ymax = float(yvals.max()) # Position the image according to coords shape = img.shape a = [(0, shape[-2]), (shape[-1] - 1, shape[-2]), (shape[-1] - 1, 1), (0, 1)] b = [(ymin, xmin), (ymax, xmin), (ymax, xmax), (ymin, xmax)] quad1 = QPolygonF() quad2 = QPolygonF() for p, q in zip(a, b): quad1.append(QPointF(*p)) quad2.append(QPointF(*q)) transform = QTransform() QTransform.quadToQuad(quad1, quad2, transform) kwargs['transform'] = transform if 'xvals' not in kwargs: kwargs['xvals'] = np.asarray(img.coords[img.dims[0]]) # Set the timeline axis label from dims self.ui.roiPlot.setLabel('bottom', img.dims[0]) # Label the image axes self.axesItem.setLabel('left', img.dims[-2]) self.axesItem.setLabel('bottom', img.dims[-1]) # Add a bit more size self.ui.roiPlot.setMinimumSize(QSize(0, 70)) # Bind coords from the xarray to the timeline axis super(XArrayView, self).setImage(img, **kwargs) def updateImage(self, autoHistogramRange=True): if hasattr(self.image, 'dims'): ## Redraw image on screen if self.image is None: return image = self.getProcessedImage() if autoHistogramRange: self.ui.histogram.setHistogramRange(self.levelMin, self.levelMax) # Transpose image into order expected by ImageItem if self.imageItem.axisOrder == 'col-major': axorder = ['t', 'x', 'y', 'c'] else: axorder = ['t', 'y', 'x', 'c'] axorder = [ self.axes[ax] for ax in axorder if self.axes[ax] is not None ] ax_swap = [image.dims[ax_index] for ax_index in axorder] image = image.transpose(*ax_swap) # Select time index if self.axes['t'] is not None: self.ui.roiPlot.show() image = image[self.currentIndex] self.imageItem.updateImage(np.asarray(image)) else: super(XArrayView, self).updateImage(autoHistogramRange) def quickMinMax(self, data): """ Estimate the min/max values of *data* by subsampling. MODIFIED TO USE THE 99TH PERCENTILE instead of max. """ if data is None: return 0, 0 sl = slice(None, None, max(1, int(data.size // 1e6))) data = np.asarray(data[sl]) levels = (np.nanmin(data), np.nanpercentile( np.where(data < np.nanmax(data), data, np.nanmin(data)), 99)) return [levels]