def export_plot(plt, filename, width=None, height=None): """ Export an existing plot to an image and save with given filename. Optionally, image width and height in pixels can be specified. """ e = ImageExporter(plt.plotItem) if width is not None: e.parameters()['width'] = width if height is not None: e.parameters()['height'] = height e.export(filename)
def export_plot(plt, filename, width=None, height=None): """ Export an existing plot to an image and save with given filename. Optionally, image width and height in pixels can be specified. """ e = ImageExporter(plt.plotItem) if width is not None: e.parameters()['width'] = width if height is not None: e.parameters()['height'] = height e.export(filename)
class SaveChartDialog(QDialog, Ui_saveChartDialog): ''' Save Chart dialog ''' def __init__(self, parent, name, plot, statusbar=None): super(SaveChartDialog, self).__init__(parent) self.setupUi(self) self.name = name self.plot = plot self.exporter = ImageExporter(self.plot.getPlotItem()) self.__x = self.plot.size().width() self.__y = self.plot.size().height() self.__aspectRatio = self.__x / self.__y self.widthPixels.setValue(self.__x) self.heightPixels.setValue(self.__y) self.statusbar = statusbar self.__dialog = QFileDialog(parent=self) def accept(self): formats = "Portable Network Graphic (*.png)" file_name = self.__dialog.getSaveFileName(self, 'Export Chart', f"{self.name}.png", formats) if file_name: output_file = str(file_name[0]).strip() if len(output_file) == 0: return else: self.exporter.parameters()['width'] = self.widthPixels.value() self.__force_to_int('height') self.__force_to_int('width') self.exporter.export(output_file) if self.statusbar is not None: self.statusbar.showMessage( f"Saved {self.name} to {output_file}", 5000) QDialog.accept(self) def __force_to_int(self, param_name): h = self.exporter.params.param(param_name) orig_h = int(self.exporter.parameters()[param_name]) with block_signals(h): h.setValue(orig_h + 0.1) h.setValue(orig_h) def set_height(self, newWidth): ''' Updates the height as the width changes according to the aspect ratio. :param newWidth: the new width. ''' self.heightPixels.setValue( int(math.floor(newWidth / self.__aspectRatio)))
def draw_image(self, index, color, x, y, split_name_list): self.plt.plot(x, y, pen=pg.mkPen(QColor(color[0], color[1], color[2]))) pltItem = self.plt.getPlotItem() left_axis = pltItem.getAxis("left") left_axis.enableAutoSIPrefix(False) font = QFont() font.setPixelSize(16) left_axis.tickFont = font bottom_axis = pltItem.getAxis("bottom") bottom_axis.tickFont = font exporter = ImageExporter(self.plt.getPlotItem()) exporter.parameters()['width'] = 800 exporter.parameters()['height'] = 600 split_name = 'tmp/' + 'split_' + str(index) + '.png' exporter.export(split_name) split_name_list.append(split_name)
def getQImage(self, resX=None,resY=None): #zoom the the chosen colorrange: r = self.ui.histogram.region.getRegion() self.ui.histogram.vb.setYRange(*r) #create ImageExporters: mainExp = ImageExporter(self.view) colorAxisExp = ImageExporter(self.ui.histogram.axis) colorBarExp = ImageExporter(self.ui.histogram.gradient) if resX or resY: #get size-x: mainW = mainExp.getTargetRect().width() colorAxisW = colorAxisExp.getTargetRect().width() colorBarW = colorBarExp.getTargetRect().width() #all parts have the same height: mainExp.parameters()['height'] = resY colorAxisExp.parameters()['height'] = resY colorBarExp.parameters()['height'] = resY #size x is proportional: sumWidth = mainW + colorAxisW + colorBarW mainExp.parameters()['width'] = resX * mainW / sumWidth colorAxisExp.parameters()['width'] = resX * colorAxisW / sumWidth colorBarExp.parameters()['width'] = resX * colorBarW / sumWidth #create QImages: main =mainExp.export(toBytes=True) colorAxis =colorAxisExp.export(toBytes=True) colorBar = colorBarExp.export(toBytes=True) #define the size: x = main.width() + colorAxis.width() + colorBar.width() y = main.height() #to get everything in the same height: yOffs = [0,0.5*(y-colorAxis.height()),0.5*(y-colorBar.height())] result = QtGui.QImage(x, y ,QtGui.QImage.Format_RGB32) #the colorbar is a bit smaller that the rest. to exclude black lines paint all white: result.fill(QtCore.Qt.white) painter = QtGui.QPainter(result) posX = 0 for img,y in zip((main,colorAxis,colorBar),yOffs): #draw every part in different positions: painter.drawImage(posX, y, img) posX += img.width() painter.end() return result
def save(self): self.timer.stop() self.deque = deque() firstName = self.plots.lineName.text() firstName = firstName[0].upper() + firstName[1:] lastName = self.plots.lineSurname.text().split(' ') lastName[-1] = lastName[-1][0].upper() + lastName[-1][1:] lastName = ' '.join(lastName) name = '{} {}'.format(firstName, lastName) self.globalScores[name] = [ int(self.plots.lineAge.text()), self.maxPower, self.maxFrequency ] self.localScores[name] = [ int(self.plots.lineAge.text()), self.maxPower, self.maxFrequency ] # update highscores self.dumpScores() # update scores window self.updateScoresSignal.emit() pen = pg.mkPen(color=(0, 0, 0), width=2) pg.setConfigOption('background', 'w') timePlot = pg.PlotWidget() timePlot.setRange(yRange=[1.2 * -2**15, 1.2 * 2**15]) timePlot.setBackground(None) timePlot.hideAxis('left') timePlot.hideAxis('bottom') timePlot.resize(800, 200) timeCurve = timePlot.plot(self.timeAxis, self.audioData[::self.DECIMATION], pen=pen) # create rotated version of spectrum # labelStyle = {'color': '#000', 'font-size': '16px'} # spectrumPlot = pg.PlotWidget() # # spectrumPlot.setTitle(title='Power Spectral Density', **labelStyle) # # spectrumPlot.setLabel('bottom', 'frequency (Hz)', **labelStyle) # # spectrumPlot.setLabel('left', 'power spectral density (dB)', **labelStyle) # spectrumPlot.getAxis("left").setWidth(200) # spectrumPlot.getAxis('left').setPen(pen) # spectrumPlot.getAxis('bottom').setPen(pen) # #spectrumPlot.setBackground(None) # spectrumPlot.getPlotItem().setLogMode(True, False) # spectrumPlot.getPlotItem().setRange( # xRange=[1, np.log10(self.SAMPLE_RATE // 2)], # yRange=[0, self.SPECTRUM_MAX]) # spectrumPlot.getAxis('left').setTicks( # [[(x, str(x)) for x in range(self.SPECTRUM_MIN, self.SPECTRUM_MAX, 20)]]) # spectrumPlot.getAxis('bottom').setTicks( # [[(x, str(int(10**x))) for x in [1, 2, 3, 4, 5]]]) # spectrumCurve = spectrumPlot.plot(self.spectrumScale, self.maxSpectrum, pen=pen) # export plots to png # exporter = ImageExporter(spectrumPlot.plotItem) # exporter.parameters()['width'] = 2000 # exporter.export('images/spectrum.png') exporter = ImageExporter(timePlot.plotItem) exporter.parameters()['width'] = 2000 exporter.export('images/timeseries.png') exporter = ImageExporter(self.spectrogramImage) exporter.parameters()['width'] = 2000 exporter.export('images/spectrogram.png') diplomaPath = createDiploma(firstName, lastName, self.maxPower, self.maxFrequency) time.sleep(0.5)
def plot(self, dataToPlot, times=None, save=False): if not dataToPlot.equals(self.data): self.minYLeft, self.maxYLeft, self.minYRight, self.maxYRight = None, None, None, None self.data = dataToPlot self.data.to_clipboard() self.plotItem.clear() try: self.plotItem.scene().removeItem(self.plot2) except AttributeError: pass x1 = self.data.iloc[:, 0] y1 = self.data.iloc[:, 1] y2 = self.data.iloc[:, 2] x2 = self.data.iloc[:, 3] y3 = self.data.iloc[:, 4] for g in (x1, y1, y2, x2, y3): g.dropna(inplace=True) x1 = [i.to_pydatetime().timestamp() for i in x1.to_list()] x2 = [i.to_pydatetime().timestamp() for i in x2.to_list()] self.plotItem.addLegend().clear() self.plotItem.plot(x1, y1, pen=pg.mkPen('g', width=3), name='Pressure') self.plotItem.plot(x1, y2, pen=pg.mkPen('r', width=3), name="Temperature") self.plot2.clear() self.plotItem.scene().addItem(self.plot2) self.plotItem.getAxis('right').linkToView(self.plot2) self.plot2.setXLink(self.plotItem) self.updateViews() self.plotItem.vb.sigResized.connect(self.updateViews) curve3 = pg.PlotDataItem(x2, y3, name='Depth', pen=pg.mkPen('b', width=3)) self.plot2.addItem(curve3) self.plotItem.addLegend().addItem(curve3, 'Depth') self.plotItem.getViewBox().autoRange() range = self.plotItem.getViewBox().viewRange()[0] minXFirstLeft, maxXFirstLeft = range[0], range[1] self.plot2.autoRange() range = self.plot2.viewRange()[0] minXFirstRight, maxXFirstRight = range[0], range[1] self.plot2.setXRange(min(minXFirstRight, minXFirstLeft), max(maxXFirstRight, maxXFirstLeft)) if (self.minYLeft, self.maxYLeft, self.minYRight, self.maxYRight) == (None, None, None, None): range = self.plotItem.getViewBox().viewRange()[1] self.minYLeft, self.maxYLeft = range[0], range[1] range = self.plot2.viewRange()[1] self.minYRight, self.maxYRight = range[0], range[1] if save: exporter = ImageExporter(self.plotItem) exporter.parameters()['width'] = 580 exporter.parameters()['height'] = 450 buffer = QBuffer() buffer.open(QIODevice.ReadWrite) exporter.export(toBytes=True).save(buffer, "PNG") buffer.seek(0) fig = BytesIO(buffer.readAll()) return fig else: if times is not None: self.button1.setVisible(True) self.button2.setVisible(True) vLines1, vLines2 = [self.makeInfLine(time, 0) for time in times[0]], \ [self.makeInfLine(time, 1) for time in times[1]] for line in chain(vLines1, vLines2): self.plotItem.addItem(line) line.infLineSignal.connect(self.emittingToMain)