def get_lut(cmap_name, alpha=255): """ Get the colour lookup table by name. Handles Matplotlib as well as pyqtgraph built in colormaps. Pyqtgraph is a bit rubbish here - to load a predefined color map and extract the lookup table we need to create a GradientEditorItem even though we're not doing anything involving the GUI. """ if not cmap_name: cmap_name = "jet" gradient = pg.GradientEditorItem() try: gradient.loadPreset(cmap_name) LOG.debug("Loaded standard LUT: %s", cmap_name) except KeyError: gradient.restoreState(get_lut_from_matplotlib(cmap_name)) LOG.debug("Loaded Matplotlib LUT: %s", cmap_name) lut = gradient.getLookupTable(nPts=512, alpha=True) LOG.debug("LUT: %s", lut) for entry in lut: entry[3] = alpha return lut
def init_opdet_ui(self): self._opdet_plots = [] self._pmts = [] self._arapucas = [] self._opdetscales = [] for tpc in range(self._geometry.nTPCs() * self._geometry.nCryos()): opdet_plot = self._opdet_views[tpc].addPlot() opdet_plot.setLabel(axis='left', text='Y [cm]') opdet_plot.setLabel(axis='bottom', text='Z [cm]') this_scale = pg.GradientEditorItem(orientation='right') self._opdet_views[tpc].addItem(this_scale, 0, 1) these_pmts = pmts(self._geometry, tpc=tpc, pmtscale=this_scale) opdet_plot.addItem(these_pmts) these_pmts.sigClicked.connect(self.pmtClickWorker) these_pmts.scene().sigMouseMoved.connect(these_pmts.onMove) these_arapucas = arapucas(self._geometry, tpc=tpc) opdet_plot.addItem(these_arapucas) these_arapucas.sigClicked.connect(self.arapucaClickWorker) these_arapucas.scene().sigMouseMoved.connect(these_arapucas.onMove) self._opdet_plots.append(opdet_plot) self._pmts.append(these_pmts) self._arapucas.append(these_arapucas) self._opdetscales.append(this_scale)
def _initialise_series(self, channels): if self.plot is not None: self.removeItem(self.plot.image_item) self.plot = None try: self.data_names, _ = extract_scalar_channels(channels) except ValueError as e: self.error.emit(str(e)) if not self.data_names: self.error.emit("No scalar result channels to display") hints_for_channels = { name: channels[name].get("display_hints", {}) for name in self.data_names } def bounds(schema): return (schema.get(n, None) for n in ("min", "max", "increment")) self.colorbar = pyqtgraph.GradientEditorItem(orientation='right', allowAdd=False) pi = self.getPlotItem() pi.layout.addItem(self.colorbar, 2, 3) self.colorbar.sigGradientChanged.connect(self._update_colorbar) image_item = pyqtgraph.ImageItem() self.addItem(image_item) self.plot = _ImagePlot(image_item, self.data_names[0], *bounds(self.x_schema), *bounds(self.y_schema), hints_for_channels, self.colorbar) self.ready.emit()
def __init__(self, index, globals={}, **kwargs): super().__init__(**kwargs) self.index = index self.globals = globals self.connected = False self.name = "" self.camera = None self.capture = False self.trig = 2 self.plotArea = pg.GraphicsLayoutWidget(self) box = pg.ViewBox(lockAspect=1) self.plotArea.addItem(box) self.plot = pg.ImageItem() box.addItem(self.plot) self.grad = pg.GradientEditorItem() try: state = pickle.load(open("grad.p", "rb")) except: state = None if state: self.grad.restoreState(state) box.addItem(self.grad) self.timer = QTimer() self.timer.timeout.connect(self.sayCheese) self.time = time.perf_counter() self.trigger.connect(self.draw) self.trigType = None self.connectCamera() if self.connected: self.initUI() self.getImageThread = GetImageThread(self) self.getImageThread.start() self.grad.sigGradientChangeFinished.connect(self.gradChange) return
def __init__(self, parent=None): super().__init__(parent) self.layout = QtGui.QGraphicsGridLayout() self.setLayout(self.layout) self.gradient = pg.GradientEditorItem(orientation="right") self.axis = pg.AxisItem(orientation="left") self.layout.addItem(self.gradient, 0, 1) self.layout.addItem(self.axis, 0, 0)
def __init__(self, dm): super().__init__() self.dm = dm # self.data = pd.read_csv('./dev/voltam_data.csv').values.T # self.data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) self.data = None self.dmin = None self.dmax = None self.plt = self.plotItem # colors from cmap file color_file = os.path.abspath( resource_filename('wildcat', 'extra/voltam_color.csv')) rgbs = np.loadtxt(color_file, delimiter=',') alphas = np.full((len(rgbs), 1), 1.0) self.colors = np.append(rgbs, alphas, axis=1) # set up colorbar self.cbar = pg.GradientEditorItem(orientation='right') self.cbar.tickSize = 0 pos = np.linspace(0, 1, len(self.colors)) self.cbar.setColorMap(pg.ColorMap(pos, self.colors)) # set up colorbar axis cbar_ax = pg.AxisItem('right') self.cbar_vb = pg.ViewBox() self.plt.scene().addItem(self.cbar_vb) self.plt.layout.addItem(self.cbar, 2, 3) self.plt.layout.addItem(cbar_ax, 2, 4) cbar_ax.linkToView(self.cbar_vb) self.cbar_vb.setGeometry(self.plt.vb.sceneBoundingRect()) self.plt.vb.setMouseEnabled(False, False) self.plt.setMenuEnabled(False) # set up image item self.im = pg.ImageItem(self.data) self.plt.vb.addItem(self.im) # add marker to plot vb pen = pg.mkPen('g', width=2.0) self.row_marker = pg.InfiniteLine(angle=0, pen=pen, movable=True) self.col_marker = pg.InfiniteLine(pen=pen, movable=True) self.plt.vb.addItem(self.row_marker) self.plt.vb.addItem(self.col_marker) self.set_cp_data() # self.auto_range() # connect cbar_vb for when Y axis changes self.cbar_vb.sigYRangeChanged.connect(self.update_levels) self._update_views() self.plt.vb.sigResized.connect(self._update_views) # connect for when cp_data changes self.dm.sigCPDataChanged.connect(self.set_cp_data) self.dm.sigCPDataChanged.connect(self.find_peak)
def createSlider(self): slider = pg.GradientEditorItem(orientation='top', allowAdd=False) # print slider.__dict__ # slider.tickPen = pg.mkPen(color=(255,255,255)) slider.tickSize = 0 # print slider.gradRect slider.rectSize = 0 for i in slider.ticks: slider.setTickColor(i, QtGui.QColor(150,150,150)) return slider
def __init__(self): QtGui.QWidget.__init__(self) self.setupGUI() self.data = {'P': {}, 'Sx': {}, 'Sy': {}} self.currentShifts = {'P': 0, 'Sx': 0, 'Sy': 0} self.connectPlotButtons() self.mode = 'WaveForms' self.gw = pg.GradientEditorItem(orientation='right') self.gw.restoreState(Gradients['hot']) self.allParameters = [] self.yAxis = 'Number of sonic track'
def __init__( self, color1=TSNEPlot.createColor(225, 128, 128), color2=TSNEPlot.createColor(45, 128, 128), ): super().__init__() self.initUI() self.color1 = color1 self.color2 = color2 self.color_scale = pg.GradientEditorItem() self.color_scale.loadPreset("thermal") self.color_scale.setOrientation("right") self.color_scale.setColorMode("hsv")
import pyqtgraph as pg app = pg.mkQApp("Gradiant Editor Example") mw = pg.GraphicsView() mw.resize(800,800) mw.show() #ts = pg.TickSliderItem() #mw.setCentralItem(ts) #ts.addTick(0.5, 'r') #ts.addTick(0.9, 'b') ge = pg.GradientEditorItem() mw.setCentralItem(ge) if __name__ == '__main__': pg.exec()
colors = np.genfromtxt("colours.txt", max_rows=len(faces), usecols=(0, 1, 2, 3)) ## Mesh item will automatically compute face normals. m1 = gl.GLMeshItem(vertexes=verts, faces=faces, faceColors=colors, smooth=False, drawEdges=True, edgeColor=(1, 1, 1, 1)) m1.translate(-0.75, -0.25, 0.0) m1.setGLOptions('additive') m1.rotate(90, 0, 0, 1) grid.addItem(m1) gw = pg.GradientEditorItem(orientation='right') # load predefined color gradient GradiendMode = Gradients["rgb"] gw.restoreState(GradiendMode) ax = pg.AxisItem('left') ax.setRange(-1.0, 1.0) cb = pg.GraphicsLayoutWidget() cb.addItem(ax) cb.addItem(gw) cb.resize(100, 700) cb.show() layout.addWidget(cb, 0, 1) layout.addWidget(grid, 0, 0) layout.setColumnStretch(0, 1)
def surfMesh(self, vertexes, faces, faceValues, cmap='space', drawEdges=False, smooth=False): ''' plots data for the triangular mesh Arguments: float numpyarray vertexes: x-y coordinates of the vertices constituting the mesh note: doesn't work with 3D. need some changes int numpyarray faces: each element represents numbers of verticis constituting a face float numpyarray data str cmap: 'space' - default cmap developed by me. kinda cool :-) 'thermal' ''' nbplt = len(self.plots) # impose color scheme if cmap in Gradients: GradiendMode = Gradients[cmap] else: raise TypeError('Color Map is not defined.') # compute normalized value for color calculation nbv = len(vertexes) # number of vertexes xmin = faceValues.min() xmax = faceValues.max() if xmax != xmin: x = (faceValues - xmin) / (xmax - xmin) else: x = np.ones(len(faceValues)) * xmin # Main window containing other widgets win = QtGui.QWidget() win.setWindowTitle('isqt plot') self.windows.append(win) # leyout windget controlling layour of other widgets layout = QtGui.QGridLayout() win.setLayout(layout) # Widget - righthand side of the window allocated for the colorbar cb = pg.GraphicsLayoutWidget() # values axis ax = pg.AxisItem('left') if xmax != xmin: # here we handle arrays with all values the same # ax.setRange(np.round(xmin,2), np.round(xmax,2)) # to round numbers on ticks - doesn't work ax.setRange(xmin, xmax) else: ax.setRange(xmin, xmax + 0.0001) cb.addItem(ax) # Gradient Editor widget gw = pg.GradientEditorItem(orientation='right') # load predefined color gradient gw.restoreState(GradiendMode) # left side of the window for 3D data representation view = gl.GLViewWidget() # it's basically view.setSizePolicy(cb.sizePolicy()) # add 3D widget to the left (first column) layout.addWidget(view, 0, 0) # add colorbar to the right (second column) layout.addWidget(cb, 0, 1) # Do not allow 2nd column (colorbar) to stretch layout.setColumnStretch(1, 0) # minimal size of the colorbar layout.setColumnMinimumWidth(1, 120) # Allow 1st column (3D widget) to stretch layout.setColumnStretch(0, 1) # horizontal size set to be large to prompt colormap to a minimum size view.sizeHint = lambda: pg.QtCore.QSize(1700, 800) cb.sizeHint = lambda: pg.QtCore.QSize(100, 800) # this is to remove empty space between layout.setHorizontalSpacing(0) # set initial size of the window win.resize(800, 800) win.show() cb.addItem(gw) cm = gw.colorMap() # colors = cm.map(x) colors = cm.mapToFloat(x) # create 3D array to pass it to plotting function vetrs3D = np.zeros([nbv, 3]) if vertexes.shape == (nbv, 3): vetrs3D = vertexes else: print('Converting 2D to 3D') vetrs3D[:, :2] = vertexes # compute distance to set initial camera pozition dst = max(vertexes[:, 0].max() - vertexes[:, 0].min(), vertexes[:, 1].max() - vertexes[:, 1].min()) view.setCameraPosition(distance=dst) plt = gl.GLMeshItem(vertexes=vetrs3D, faces=faces, faceColors=colors, drawEdges=drawEdges, smooth=smooth) view.addItem(plt) self.plots.append(plt)
def __init__(self, image=None, fillHistogram=True, rgbHistogram=False, levelMode='mono'): pg.GraphicsWidget.__init__(self) self.lut = None self.imageItem = lambda: None # fake a dead weakref self.levelMode = levelMode self.rgbHistogram = rgbHistogram self.layout = QtGui.QGraphicsGridLayout() self.setLayout(self.layout) self.layout.setContentsMargins(1, 1, 1, 1) self.layout.setSpacing(0) self.vb = pg.ViewBox(parent=self) self.vb.setMaximumHeight(20) self.vb.setMinimumHeight(20) self.vb.setMouseEnabled(x=False, y=True) self.gradient = pg.GradientEditorItem() self.gradient.setOrientation('top') self.gradient.loadPreset('viridis') self.gradient.setFlag(self.gradient.ItemStacksBehindParent) self.vb.setFlag(self.gradient.ItemStacksBehindParent) self.layout.addItem(self.gradient, 0, 0) self.layout.addItem(self.vb, 1, 0) self.axis = pg.AxisItem('bottom', linkView=self.vb, maxTickLength=-10, parent=self) self.layout.addItem(self.axis, 2, 0) self.regions = [ pg.LinearRegionItem([0, 1], 'vertical', swapMode='block'), #we dont need those here #pg.LinearRegionItem([0, 1], 'vertical', swapMode='block', pen='r',brush=fn.mkBrush((255, 50, 50, 50)), span=(0., 1/3.)), #pg.LinearRegionItem([0, 1], 'vertical', swapMode='block', pen='g',brush=fn.mkBrush((50, 255, 50, 50)), span=(1/3., 2/3.)), #pg.LinearRegionItem([0, 1], 'vertical', swapMode='block', pen='b',brush=fn.mkBrush((50, 50, 255, 80)), span=(2/3., 1.)), #pg.LinearRegionItem([0, 1], 'vertical', swapMode='block', pen='w',brush=fn.mkBrush((255, 255, 255, 50)), span=(2/3., 1.)) ] for region in self.regions: region.setZValue(1000) self.vb.addItem(region) region.lines[0].addMarker('<|', 0.5) region.lines[1].addMarker('|>', 0.5) region.sigRegionChanged.connect(self.regionChanging) region.sigRegionChangeFinished.connect(self.regionChanged) self.region = self.regions[0] add = QtGui.QPainter.CompositionMode_Plus self.plots = [ pg.PlotCurveItem(pen=(200, 200, 200, 100)), # mono pg.PlotCurveItem(pen=(255, 0, 0, 100), compositionMode=add), # r pg.PlotCurveItem(pen=(0, 255, 0, 100), compositionMode=add), # g pg.PlotCurveItem(pen=(0, 0, 255, 100), compositionMode=add), # b pg.PlotCurveItem(pen=(200, 200, 200, 100), compositionMode=add), # a ] self.plot = self.plots[0] for plot in self.plots: self.vb.addItem(plot) self.fillHistogram(fillHistogram) self.range = None self.gradient.sigGradientChanged.connect(self.gradientChanged) self.vb.sigRangeChanged.connect(self.viewRangeChanged)