def initUi(self): # axes setup self.widget = InteractiveGRWidget(self) self.plot = Plot(viewport=(.1, .95, .25, .95)) self.axes = NicosTimePlotAxes(self.plot._viewport) self.axes.setWindow(0, 1, 0, 1) self.plot.addAxes(self.axes) self.plot.setLegend(True) self.plot.setLegendWidth(0.07) self.plot.offsetXLabel = -.2 self.axes.setXtickCallback(self.xtickCallBack) self.widget.addPlot(self.plot) layout = QHBoxLayout(self) layout.addWidget(self.widget) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.curves = [] # event support self.widget.cbm.addHandler(LegendEvent.ROI_CLICKED, self.on_legendItemClicked, LegendEvent) self.widget.cbm.addHandler(MouseEvent.MOUSE_MOVE, self.on_mouseMove) self.timeSeriesUpdate.connect(self.on_timeSeriesUpdate)
def main(*args): app = QtGui.QApplication(*args) grw = InteractiveGRWidget() viewport = [0.1, 0.88, 0.1, 0.88] xd = [3, 3, 10, 18, 18, 10, 10, 5, 1, 15, 20, 5, 15, 10, 7, 13, 16] yd = [3, 18, 18, 3, 18, 10, 1, 5, 10, 5, 10, 15, 15, 15, 20, 20, 8] zd = [25, 25, 25, 25, 25, -5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 25] axes = ContourAxes(viewport) axes.addCurves(PlotContour(xd, yd, zd, nx=40, ny=40)) axes.setGrid(False) plot = Plot(viewport).addAxes(axes) plot.title = "Plot contour lines using QtGR" grw.addPlot(plot) grw.resize(QtCore.QSize(500, 500)) grw.show() win = axes.getWindow() grw.update() sys.exit(app.exec_())
def __init__(self, *args, **kwargs): QtGui.QMainWindow.__init__(self, *args, **kwargs) self._grw = InteractiveGRWidget() self.setCentralWidget(self._grw) viewport = [0.1, 0.88, 0.1, 0.88] self.curve = DependentPlotCurve([0], [0], linecolor=4) self.peakbars = PeakBars([], [], linecolor=2) self.curve.dependent = [self.peakbars] axes = ClampedPlotAxes(viewport, 50, 5, 1, 2) axes.setWindow(50, 25000, 0, 100) axes.addCurves(self.curve) plot = Plot(viewport).addAxes(axes) plot.title = "QtGR Power Spectrum" plot.subTitle = "Capturing Microphone" axes.scale = gr.OPTION_X_LOG self._grw.addPlot(plot) timer = QtCore.QTimer(self) timer.timeout.connect(self.updateData) timer.start(40)
def __init__(self, parent, window, timeaxis=False): InteractiveGRWidget.__init__(self, parent) NicosPlot.__init__(self, window, timeaxis=timeaxis) self.timeaxis = timeaxis or (self.axescls == NicosTimePlotAxes) self.leftTurnedLegend = True self.statusMessage = None self.mouselocation = None self._cursor = self.cursor() self._mouseSelEnabled = self.getMouseSelectionEnabled() self._markertype = gr.MARKERTYPE_OMARK dictPrintType = dict(gr.PRINT_TYPE) for prtype in [gr.PRINT_JPEG, gr.PRINT_TIF]: dictPrintType.pop(prtype) self._saveTypes = (";;".join(dictPrintType.values()) + ";;" + ";;".join(gr.GRAPHIC_TYPE.values())) self._saveName = None self._color = ColorIndexGenerator() self._plot = Plot(viewport=(.1, .85, .15, .88)) self._plot.setLegendWidth(0.05) self._axes = self.axescls(viewport=self._plot.viewport) self._axes.backgroundColor = 0 self._plot.addAxes(self._axes) self._plot.title = self.titleString() self.addPlot(self._plot) guiConn = GUIConnector(self) guiConn.connect(LegendEvent.ROI_CLICKED, self.on_legendItemClicked, LegendEvent) guiConn.connect(ROIEvent.ROI_CLICKED, self.on_roiItemClicked, ROIEvent) guiConn.connect(MouseEvent.MOUSE_PRESS, self.on_fitPicker_selected) guiConn.connect(MouseEvent.MOUSE_MOVE, self.on_mouseMove) self.logXinDomain.connect(self.on_logXinDomain) self.logYinDomain.connect(self.on_logYinDomain) self.setLegend(True) self.updateDisplay()
def main(*args): app = QtWidgets.QApplication(*args) grw = InteractiveGRWidget() viewport = [0.1, 0.88, 0.1, 0.88] z = readfile( os.path.join(os.path.dirname(os.path.realpath(__file__)), "fecr.dat")) zd = np.asarray(z) xd = yd = np.arange(1, 201) axes = ContourAxes(viewport) axes.addCurves(PlotSurface(xd, yd, zd, option=gr.OPTION_CELL_ARRAY)) axes.addCurves(PlotContour(xd, yd, zd)) axes.setGrid(False) plot = Plot(viewport).addAxes(axes) plot.title = "Plot surface and contour lines using QtGR" grw.addPlot(plot) grw.resize(QtCore.QSize(500, 500)) grw.show() win = axes.getWindow() grw.update() sys.exit(app.exec_())
def main(*args): app = QtGui.QApplication(*args) grw = InteractiveGRWidget() viewport = [0.1, 0.88, 0.1, 0.88] z = readfile(os.path.join(os.path.dirname(os.path.realpath(__file__)), "fecr.dat")) zd = np.asarray(z) xd = yd = np.arange(1, 201) axes = ContourAxes(viewport) axes.addCurves(PlotSurface(xd, yd, zd, option=gr.OPTION_CELL_ARRAY)) axes.addCurves(PlotContour(xd, yd, zd)) axes.setGrid(False) plot = Plot(viewport).addAxes(axes) plot.title = "Plot surface and contour lines using QtGR" grw.addPlot(plot) grw.resize(QtCore.QSize(500, 500)) grw.show() win = axes.getWindow() grw.update() sys.exit(app.exec_())
def __init__(self, *args, **kwargs): QtGui.QMainWindow.__init__(self, *args, **kwargs) self._grw = InteractiveGRWidget() self.setCentralWidget(self._grw) viewport = [0.1, 0.88, 0.1, 0.88] x = arange(0, 2 * pi, 0.01) y = sin(x) self.curve = PlotCurve(x, y) axes = ScaledPlotAxes(viewport) axes.addCurves(self.curve) plot = Plot(viewport).addAxes(axes) plot.title = "QtGR Timer example" plot.subTitle = "Plotting Live-Data" plot.xlabel = "t" plot.ylabel = "sin(t)" plot.autoscale = PlotAxes.SCALE_X | PlotAxes.SCALE_Y self._grw.addPlot(plot) timer = QtCore.QTimer(self) timer.timeout.connect(self.updateData) timer.start(40)
if __name__ == "__main__": import sys from gr import pygr logging.basicConfig(level=logging.CRITICAL) for name in [__name__, pygr.base.__name__, pygr.__name__]: logging.getLogger(name).setLevel(logging.DEBUG) app = QtGui.QApplication(sys.argv) grw = InteractiveGRWidget() grw.resize(QtCore.QSize(500, 500)) viewport = [0.1, 0.9, 0.1, 0.88] x = [-3.3 + t * .1 for t in range(66)] y = [t**5 - 13 * t**3 + 36 * t for t in x] n = 100 pi2_n = 2. * math.pi / n x2 = [i * pi2_n for i in range(0, n + 1)] y2 = map(lambda xi: math.sin(xi), x2) plot = Plot(viewport).addAxes(PlotAxes().plot(x, y), PlotAxes().plot(x2, y2)) plot.title, plot.subTitle = "foo", "bar" plot.xlabel, plot.ylabel = "x", "f(x)" grw.addPlot(plot) grw.show() grw.update() sys.exit(app.exec_())
def plot(self, *args, **kwargs): plot = Plot() axes = PlotAxes(plot.viewport) axes.plot(*args, **kwargs) plot.addAxes(axes) return self.addPlot(plot)
logging.getLogger(name).setLevel(logging.DEBUG) app = QApplication(sys.argv) grw = InteractiveGRWidget() grw.resize(QtCore.QSize(500, 500)) viewport = [0.1, 0.45, 0.1, 0.88] vp2 = [.6, .95, .1, .88] x = [-3.3 + t * .1 for t in range(66)] y = [t ** 5 - 13 * t ** 3 + 36 * t for t in x] n = 100 pi2_n = 2.*math.pi / n x2 = [i * pi2_n for i in range(0, n + 1)] y2 = map(lambda xi: math.sin(xi), x2) plot = Plot(viewport).addAxes(PlotAxes(viewport).plot(x, y), PlotAxes(viewport).plot(x2, y2)) plot.title, plot.subTitle = "foo", "bar" plot.xlabel, plot.ylabel = "x", "f(x)" plot2 = Plot(vp2).addAxes(PlotAxes(vp2).plot(x2, y2)) plot2.title, plot2.subTitle = "Title", "Subtitle" plot2.xlabel = "x" grw.addPlot(plot) grw.addPlot(plot2) grw.show() grw.update() sys.exit(app.exec_())
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) uic.loadUi(os.path.join(os.path.dirname(os.path.realpath(__file__)), "qtgrdemo.ui"), self) dictPrintType = dict(gr.PRINT_TYPE) map(dictPrintType.pop, [gr.PRINT_JPEG, gr.PRINT_TIF]) self._saveTypes = (";;".join(dictPrintType.values()) + ";;" + ";;".join(gr.GRAPHIC_TYPE.values())) self._saveName = None self._title = unicode(self.windowTitle()) self._startupTime = time.time() self._chkLogX.stateChanged.connect(self._logXClicked) self._chkLogY.stateChanged.connect(self._logYClicked) self._chkGrid.stateChanged.connect(self._gridClicked) self._chkErr.stateChanged.connect(self._errorsClicked) self._chkKeepRatio.stateChanged.connect(self._keepRatioClicked) self._btnReset.clicked.connect(self._resetClicked) self._btnPick.clicked.connect(self._pickClicked) self._shell.returnPressed.connect(self._shellEx) self._actionSave.triggered.connect(self.save) self._actionPrint.triggered.connect(self.printGR) self._gr.logXinDomain.connect(self._logXinDomain) self._gr.logYinDomain.connect(self._logYinDomain) self._gr.modePick.connect(self._pickModeChanged) guiConn = GUIConnector(self._gr) guiConn.connect(MouseEvent.MOUSE_MOVE, self.mouseMoveGr) guiConn.connect(PickEvent.PICK_PRESS, self.pointPickGr) guiConn.connect(LegendEvent.ROI_CLICKED, self.legendClick) guiConn.connect(LegendEvent.ROI_OVER, self.legendOver) x = [-3.3 + t * .1 for t in range(66)] y = [t ** 5 - 13 * t ** 3 + 36 * t for t in x] x2 = [-3.5 + i * .5 for i in range(0, 15)] y2 = x2 dneg = map(lambda y: y - 0.25 * abs(y), y) dpos = map(lambda y: y + 0.25 * abs(y), y) self._errBar = ErrorBar(x, y, dneg, dpos) self._curveFoo = PlotCurve(x, y, legend="foo bar") axes = PlotAxes().addCurves(self._curveFoo) axes.setXtickCallback(self._xtickCallBack) self._plot = Plot((.1, .92, .2, .88)).addAxes(axes, PlotAxes(drawX=False).plot(x2, y2)) self._plot.offsetXLabel = -.1 self._plot2 = Plot((.1, .95, .15, .88)).addAxes(PlotAxes().addCurves(PlotCurve(x2, y2, legend="second"))) self._plot.title = "QtGR Demo" self._plot.subTitle = "Multiple Axes Example" self._plot.xlabel = "x" self._plot.ylabel = "f(x)" self._plot.setLegend(True) self._gr.addPlot(self._plot) self._plot2.title = "Second Widget" self._plot2.subTitle = "Linear Example (less interactive)" self._plot2.xlabel = "x2" self._plot2.ylabel = "f2(x2)" self._plot2.setLegend(True) self._plot2.setGrid(False) self._gr2.addPlot(self._plot2)
class MainWindow(QtGui.QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) uic.loadUi(os.path.join(os.path.dirname(os.path.realpath(__file__)), "qtgrdemo.ui"), self) dictPrintType = dict(gr.PRINT_TYPE) map(dictPrintType.pop, [gr.PRINT_JPEG, gr.PRINT_TIF]) self._saveTypes = (";;".join(dictPrintType.values()) + ";;" + ";;".join(gr.GRAPHIC_TYPE.values())) self._saveName = None self._title = unicode(self.windowTitle()) self._startupTime = time.time() self._chkLogX.stateChanged.connect(self._logXClicked) self._chkLogY.stateChanged.connect(self._logYClicked) self._chkGrid.stateChanged.connect(self._gridClicked) self._chkErr.stateChanged.connect(self._errorsClicked) self._chkKeepRatio.stateChanged.connect(self._keepRatioClicked) self._btnReset.clicked.connect(self._resetClicked) self._btnPick.clicked.connect(self._pickClicked) self._shell.returnPressed.connect(self._shellEx) self._actionSave.triggered.connect(self.save) self._actionPrint.triggered.connect(self.printGR) self._gr.logXinDomain.connect(self._logXinDomain) self._gr.logYinDomain.connect(self._logYinDomain) self._gr.modePick.connect(self._pickModeChanged) guiConn = GUIConnector(self._gr) guiConn.connect(MouseEvent.MOUSE_MOVE, self.mouseMoveGr) guiConn.connect(PickEvent.PICK_PRESS, self.pointPickGr) guiConn.connect(LegendEvent.ROI_CLICKED, self.legendClick) guiConn.connect(LegendEvent.ROI_OVER, self.legendOver) x = [-3.3 + t * .1 for t in range(66)] y = [t ** 5 - 13 * t ** 3 + 36 * t for t in x] x2 = [-3.5 + i * .5 for i in range(0, 15)] y2 = x2 dneg = map(lambda y: y - 0.25 * abs(y), y) dpos = map(lambda y: y + 0.25 * abs(y), y) self._errBar = ErrorBar(x, y, dneg, dpos) self._curveFoo = PlotCurve(x, y, legend="foo bar") axes = PlotAxes().addCurves(self._curveFoo) axes.setXtickCallback(self._xtickCallBack) self._plot = Plot((.1, .92, .2, .88)).addAxes(axes, PlotAxes(drawX=False).plot(x2, y2)) self._plot.offsetXLabel = -.1 self._plot2 = Plot((.1, .95, .15, .88)).addAxes(PlotAxes().addCurves(PlotCurve(x2, y2, legend="second"))) self._plot.title = "QtGR Demo" self._plot.subTitle = "Multiple Axes Example" self._plot.xlabel = "x" self._plot.ylabel = "f(x)" self._plot.setLegend(True) self._gr.addPlot(self._plot) self._plot2.title = "Second Widget" self._plot2.subTitle = "Linear Example (less interactive)" self._plot2.xlabel = "x2" self._plot2.ylabel = "f2(x2)" self._plot2.setLegend(True) self._plot2.setGrid(False) self._gr2.addPlot(self._plot2) def save(self): qpath = QtGui.QFileDialog.getSaveFileName(self, "", "", self._saveTypes, gr.PRINT_TYPE[gr.PRINT_PDF]) if qpath: path = unicode(qpath) (_p, suffix) = os.path.splitext(path) suffix = suffix.lower() if suffix and (suffix[1:] in gr.PRINT_TYPE.keys() or suffix[1:] in gr.GRAPHIC_TYPE): self._gr.save(path) self._saveName = os.path.basename(path) self.setWindowTitle(self._title + " - %s" % self._saveName) else: raise Exception("Unsupported file format") def printGR(self): if self._saveName: title = "GR_Demo-" + self._saveName else: title = "GR_Demo-untitled" self._gr.printDialog(title) def mouseMoveGr(self, event): dc = event.getDC() ndc = event.getNDC() wc = event.getWC(self._plot.viewport) self._statusbar.showMessage("DC: (%4d, %4d)\t " % (dc.x, dc.y) + "NDC: (%3.2f, %3.2f)\t " % (ndc.x, ndc.y) + "WC: (%3.2f, %3.2f)" % (wc.x, wc.y)) self._lblOverLegend.setText("") def pointPickGr(self, event): p = event.getWC(event.viewport) if p.x < 0: self._lblPickX.setText("%4.2f" % p.x) else: self._lblPickX.setText(" %4.2f" % p.x) if p.y < 0: self._lblPickY.setText("%4.2f" % p.y) else: self._lblPickY.setText(" %4.2f" % p.y) def legendClick(self, event): if event.getButtons() & MouseEvent.LEFT_BUTTON: event.curve.visible = not event.curve.visible self._gr.update() def legendOver(self, event): self._lblOverLegend.setText(event.curve.legend) def _xtickCallBack(self, x, y, svalue): gr.setcharup(1., 1.) gr.settextalign(gr.TEXT_HALIGN_LEFT, gr.TEXT_VALIGN_TOP) try: gr.text(x, y, "%s (%s)" % (time.strftime("%H:%M:%S", time.localtime(self._startupTime + float(svalue))), svalue)) except ValueError: gr.text(x, y, svalue) gr.setcharup(0., 1.) def _errorsClicked(self, state): if self._chkErr.isChecked(): self._curveFoo.errorBar1 = self._errBar else: self._curveFoo.errorBar1 = None self._gr.update() def _keepRatioClicked(self, state): self._gr.keepRatio = self._chkKeepRatio.isChecked() self._gr.update() def _gridClicked(self, state): self._plot.setGrid(self._chkGrid.isChecked()) self._gr.update() def _logXClicked(self, state): self._plot.setLogX(self._chkLogX.isChecked()) self._gr.update() def _logYClicked(self, state): self._plot.setLogY(self._chkLogY.isChecked()) self._gr.update() def _resetClicked(self): self._plot.reset() self._gr.update() def _pickClicked(self): self._gr.setPickMode(True) def _pickModeChanged(self, bool): self._btnPick.setChecked(bool) @QtCore.pyqtSlot() def _shellEx(self): input = str(self._shell.text()) exec input self._shell.clear() self._gr.update() def _logXinDomain(self, bool): self._chkLogX.setEnabled(bool) if not bool: self._chkLogX.setChecked(bool) def _logYinDomain(self, bool): self._chkLogY.setEnabled(bool) if not bool: self._chkLogY.setChecked(bool)
def __init__(self, *args, **kwargs): while not shared_memory['data_fresh']: pass super(MainWindow, self).__init__(*args, **kwargs) uic.loadUi(os.path.join(os.path.dirname(os.path.realpath(__file__)), "second.ui"), self) self.monitor_mode = False self.state = 'Connecting...' self.prev_time = time.time() self._heat_capacity_spin.valueChanged.connect(self.updateHeatCapacity) self._heat_capacity_spin.setDecimals(4) self._heat_capacity_spin.setMaximum(15.00) # Will we ever heat hydrogen? self._heat_capacity_spin.setSingleStep(0.0001) self._mass_spin.valueChanged.connect(self.updateMass) self._mass_spin.setDecimals(4) self._mass_spin.setMaximum(1000.00) self._mass_spin.setSingleStep(0.0001) self._emissivity_spin.valueChanged.connect(self.updateEmissivity) self._emissivity_spin.setDecimals(4) self._emissivity_spin.setMaximum(1.00) self._emissivity_spin.setSingleStep(0.0001) self._area_spin.valueChanged.connect(self.updateArea) self._area_spin.setDecimals(4) self._area_spin.setMaximum(1000.00) self._area_spin.setSingleStep(0.0001) self._resistance_spin.valueChanged.connect(self.updateResistance) self._resistance_spin.setDecimals(1) self._resistance_spin.setMaximum(1000.0) self._resistance_spin.setSingleStep(0.1) self._voltage_spin.valueChanged.connect(self.updateVoltage) self._voltage_spin.setDecimals(2) self._voltage_spin.setMaximum(1000.00) self._voltage_spin.setSingleStep(0.01) self._p_spin.valueChanged.connect(self.updateP) self._p_spin.setDecimals(4) self._p_spin.setMaximum(2.00) self._p_spin.setSingleStep(0.0001) self._i_spin.valueChanged.connect(self.updateI) self._i_spin.setDecimals(4) self._i_spin.setMaximum(2.00) self._i_spin.setSingleStep(0.0001) self._d_spin.valueChanged.connect(self.updateD) self._d_spin.setDecimals(4) self._d_spin.setMaximum(2.00) self._d_spin.setSingleStep(0.0001) self._target_spin.valueChanged.connect(self.updateTarget) self._target_spin.setDecimals(2) self._target_spin.setMaximum(500.00) self._target_spin.setSingleStep(0.01) self._monitor_check.stateChanged.connect(self.updateMonitor) self._btn_start.clicked.connect(self.startProcess) self._btn_stop.clicked.connect(self.stopProcess) self._state_out_label.setText(self.state) try: self._heat_capacity_spin.setValue(shared_memory['heatCapacity']) self._mass_spin.setValue(shared_memory['mass']) self._emissivity_spin.setValue(shared_memory['emissivity']) self._area_spin.setValue(shared_memory['area']) self._resistance_spin.setValue(shared_memory['resistance']) self._voltage_spin.setValue(shared_memory['voltage']) self._p_spin.setValue(shared_memory['p']) self._i_spin.setValue(shared_memory['i']) self._d_spin.setValue(shared_memory['d']) except: pass # palette = self._ambient_lcd.palette() # # foreground color # palette.setColor(palette.WindowText, QtGui.QColor(0, 0, 0)) # # background color # palette.setColor(palette.Background, QtGui.QColor(0, 0, 0)) # # "light" border # # palette.setColor(palette.Light, QtGui.QColor(255, 0, 0)) # # "dark" border # palette.setColor(palette.Dark, QtGui.QColor(0, 0, 0)) # # set the palette # self._ambient_lcd.setPalette(palette) # self._bath_lcd.setPalette(palette) # self._ambient_lcd.display(0.0) # self._bath_lcd.display(0.0) x = [1.0] y = [shared_memory['bath_temp']] xe = [1.0] ye = [shared_memory['env_temp']] viewport = [0.1, 0.95, 0.1, 0.95] self.env_curve = PlotCurve(xe, ye, legend = "Environment") self.env_curve.linetype = gr.LINETYPE_DASHED self.env_curve.linecolor = 7 self.bath_curve = PlotCurve(x, y, legend = "Bath Medium") axes = PlotAxes(viewport) # axes.addCurves(self.env_curve) axes.addCurves(self.bath_curve) self._plot = Plot(viewport).addAxes(axes) self._plot.title = "System Temperatures" #self._plot.subTitle = "live data" self._plot.xlabel = "Seconds" self._plot.ylabel = "Celsius" self._plot.setLegend(True) self._plot.autoscale = PlotAxes.SCALE_X | PlotAxes.SCALE_Y self._stage.addPlot(self._plot) timer = QtCore.QTimer(self) timer.timeout.connect(self.updateData) timer.start(5000)
class MainWindow(QtGui.QMainWindow): def __init__(self, *args, **kwargs): while not shared_memory["data_fresh"]: pass super(MainWindow, self).__init__(*args, **kwargs) uic.loadUi(os.path.join(os.path.dirname(os.path.realpath(__file__)), "second.ui"), self) self.monitor_mode = False self.state = "Connecting..." self.prev_time = time.time() self._heat_capacity_spin.valueChanged.connect(self.updateHeatCapacity) self._heat_capacity_spin.setDecimals(4) self._heat_capacity_spin.setMaximum(15.00) # Will we ever heat hydrogen? self._heat_capacity_spin.setSingleStep(0.0001) self._mass_spin.valueChanged.connect(self.updateMass) self._mass_spin.setDecimals(4) self._mass_spin.setMaximum(1000.00) self._mass_spin.setSingleStep(0.0001) self._emissivity_spin.valueChanged.connect(self.updateEmissivity) self._emissivity_spin.setDecimals(4) self._emissivity_spin.setMaximum(1.00) self._emissivity_spin.setSingleStep(0.0001) self._area_spin.valueChanged.connect(self.updateArea) self._area_spin.setDecimals(4) self._area_spin.setMaximum(1000.00) self._area_spin.setSingleStep(0.0001) self._resistance_spin.valueChanged.connect(self.updateResistance) self._resistance_spin.setDecimals(1) self._resistance_spin.setMaximum(1000.0) self._resistance_spin.setSingleStep(0.1) self._voltage_spin.valueChanged.connect(self.updateVoltage) self._voltage_spin.setDecimals(2) self._voltage_spin.setMaximum(1000.00) self._voltage_spin.setSingleStep(0.01) self._p_spin.valueChanged.connect(self.updateP) self._p_spin.setDecimals(4) self._p_spin.setMaximum(2.00) self._p_spin.setSingleStep(0.0001) self._i_spin.valueChanged.connect(self.updateI) self._i_spin.setDecimals(4) self._i_spin.setMaximum(2.00) self._i_spin.setSingleStep(0.0001) self._d_spin.valueChanged.connect(self.updateD) self._d_spin.setDecimals(4) self._d_spin.setMaximum(2.00) self._d_spin.setSingleStep(0.0001) self._target_spin.valueChanged.connect(self.updateTarget) self._target_spin.setDecimals(2) self._target_spin.setMaximum(500.00) self._target_spin.setSingleStep(0.01) self._monitor_check.stateChanged.connect(self.updateMonitor) self._btn_start.clicked.connect(self.startProcess) self._btn_stop.clicked.connect(self.stopProcess) self._state_out_label.setText(self.state) try: self._heat_capacity_spin.setValue(shared_memory["heatCapacity"]) self._mass_spin.setValue(shared_memory["mass"]) self._emissivity_spin.setValue(shared_memory["emissivity"]) self._area_spin.setValue(shared_memory["area"]) self._resistance_spin.setValue(shared_memory["resistance"]) self._voltage_spin.setValue(shared_memory["voltage"]) self._p_spin.setValue(shared_memory["p"]) self._i_spin.setValue(shared_memory["i"]) self._d_spin.setValue(shared_memory["d"]) except: pass # palette = self._ambient_lcd.palette() # # foreground color # palette.setColor(palette.WindowText, QtGui.QColor(0, 0, 0)) # # background color # palette.setColor(palette.Background, QtGui.QColor(0, 0, 0)) # # "light" border # # palette.setColor(palette.Light, QtGui.QColor(255, 0, 0)) # # "dark" border # palette.setColor(palette.Dark, QtGui.QColor(0, 0, 0)) # # set the palette # self._ambient_lcd.setPalette(palette) # self._bath_lcd.setPalette(palette) # self._ambient_lcd.display(0.0) # self._bath_lcd.display(0.0) x = [1.0] y = [shared_memory["bath_temp"]] xe = [1.0] ye = [shared_memory["env_temp"]] viewport = [0.1, 0.95, 0.1, 0.95] self.env_curve = PlotCurve(xe, ye, legend="Environment") self.env_curve.linetype = gr.LINETYPE_DASHED self.env_curve.linecolor = 7 self.bath_curve = PlotCurve(x, y, legend="Bath Medium") axes = PlotAxes(viewport) # axes.addCurves(self.env_curve) axes.addCurves(self.bath_curve) self._plot = Plot(viewport).addAxes(axes) self._plot.title = "System Temperatures" # self._plot.subTitle = "live data" self._plot.xlabel = "Seconds" self._plot.ylabel = "Celsius" self._plot.setLegend(True) self._plot.autoscale = PlotAxes.SCALE_X | PlotAxes.SCALE_Y self._stage.addPlot(self._plot) timer = QtCore.QTimer(self) timer.timeout.connect(self.updateData) timer.start(5000) def _reset_curves(self): self.bath_curve.x = [0.0] self.env_curve.x = [0.0] self.bath_curve.y = [shared_memory["bath_temp"]] self.env_curve.y = [shared_memory["env_temp"]] def updateData(self): if shared_memory["data_fresh"]: t = time.time() if self.state != "Connected!": self.state = "Connected!" self._state_out_label.setText(self.state) self._env_label.setText(str(shared_memory["env_temp"])) self._bath_label_2.setText(str(shared_memory["bath_temp"])) if self.monitor_mode or shared_memory["start"]: self.env_curve.x.append(t - self.prev_time) # self.env_curve.x[-1]+5) self.bath_curve.x.append(t - self.prev_time) # self.bath_curve.x[-1]+5) self.env_curve.y.append(shared_memory["env_temp"]) self.bath_curve.y.append(shared_memory["bath_temp"]) else: self.state = "Connecting..." self._state_out_label.setText(self.state) self._env_label.setText("0.0") self._bath_label_2.setText("0.0") self.update() def updateHeatCapacity(self): shared_memory["heatCapacity"] = float(self._heat_capacity_spin.cleanText()) def updateMass(self): shared_memory["mass"] = float(self._mass_spin.cleanText()) def updateEmissivity(self): shared_memory["emissivity"] = float(self._emissivity_spin.cleanText()) def updateArea(self): shared_memory["area"] = float(self._area_spin.cleanText()) def updateResistance(self): shared_memory["resistance"] = float(self._resistance_spin.cleanText()) def updateVoltage(self): shared_memory["voltage"] = float(self._voltage_spin.cleanText()) def updateP(self): shared_memory["p"] = float(self._p_spin.cleanText()) def updateI(self): shared_memory["i"] = float(self._i_spin.cleanText()) def updateD(self): shared_memory["d"] = float(self._d_spin.cleanText()) def updateMonitor(self): if not self.monitor_mode: self._reset_curves() self._stage.update() self.monitor_mode = True else: self.monitor_mode = False def updateTarget(self): shared_memory["target"] = float(self._target_spin.cleanText()) def startProcess(self): if shared_memory["target"] is not None: self._monitor_check.setCheckState(False) self._monitor_check.setEnabled(False) self._heat_capacity_spin.setEnabled(False) self._mass_spin.setEnabled(False) self._emissivity_spin.setEnabled(False) self._area_spin.setEnabled(False) self._resistance_spin.setEnabled(False) self._voltage_spin.setEnabled(False) self._p_spin.setEnabled(False) self._i_spin.setEnabled(False) self._d_spin.setEnabled(False) self._target_spin.setEnabled(False) self._btn_start.setEnabled(False) self._reset_curves() self._stage.update() shared_memory["start"] = True def stopProcess(self): self._monitor_check.setEnabled(True) self._heat_capacity_spin.setEnabled(True) self._mass_spin.setEnabled(True) self._emissivity_spin.setEnabled(True) self._area_spin.setEnabled(True) self._resistance_spin.setEnabled(True) self._voltage_spin.setEnabled(True) self._p_spin.setEnabled(True) self._i_spin.setEnabled(True) self._d_spin.setEnabled(True) self._target_spin.setEnabled(True) self._btn_start.setEnabled(True) shared_memory["start"] = False
if __name__ == "__main__": import sys from gr import pygr logging.basicConfig(level=logging.CRITICAL) for name in [__name__, pygr.base.__name__, pygr.__name__]: logging.getLogger(name).setLevel(logging.DEBUG) app = QtGui.QApplication(sys.argv) grw = InteractiveGRWidget() grw.resize(QtCore.QSize(500, 500)) viewport = [0.1, 0.9, 0.1, 0.88] x = [-3.3 + t * .1 for t in range(66)] y = [t ** 5 - 13 * t ** 3 + 36 * t for t in x] n = 100 pi2_n = 2.*math.pi / n x2 = [i * pi2_n for i in range(0, n + 1)] y2 = map(lambda xi: math.sin(xi), x2) plot = Plot(viewport).addAxes(PlotAxes().plot(x, y), PlotAxes().plot(x2, y2)) plot.title, plot.subTitle = "foo", "bar" plot.xlabel, plot.ylabel = "x", "f(x)" grw.addPlot(plot) grw.show() grw.update() sys.exit(app.exec_())
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Draw text at an arbitrary position on the Axes using gr.pygr. """ import gr from gr.pygr import Plot, PlotAxes, PlotCurve, Text tx, ty = 0, -20 x = [-3.3 + t * .1 for t in range(66)] y = [t**5 - 13 * t**3 + 36 * t for t in x] txtfmt = "Text drawn on\n(%g, %g) with\nhalign left, valign top" plt = Plot((.1, .95, .1, .88)) plt.title = "Text on Axes Example" plt.subTitle = "Show usage of gr.pygr.Text" plt.xlabel = "x" plt.ylabel = "y" curve = PlotCurve(x, y, legend="foo bar") axes = PlotAxes(plt.viewport).addCurves(curve) axes.setWindow(-4.0, 4.0, -60.0, 40.0) text = Text(tx, -ty, txtfmt % (tx, -ty), axes, .02) plt.addAxes(axes) text2 = Text(tx, ty, txtfmt % (tx, ty), axes, .02) tbx, tby = text2.getBoundingBox() plt.drawGR() text.drawGR() text2.drawGR()
def __init__(self, widget, **kwds): OrigPlot.__init__(self, **kwds) self.widget = widget
class TrendPlot(NicosWidget, QWidget): designer_description = 'A trend plotter for one or more devices' designer_icon = ':/plotter' widgetInfo = pyqtSignal(str) timeSeriesUpdate = pyqtSignal(object) # colors = [Qt.red, Qt.darkGreen, Qt.blue, Qt.black, Qt.magenta, Qt.cyan, # Qt.darkGray] devices = PropDef( 'devices', 'QStringList', [], ''' List of devices or cache keys that the plot should display. For devices use device name. For keys use cache key with "." or "/" separator, e.g. T.heaterpower. To access items of a sequence, use subscript notation, e.g. T.userlimits[0] ''') names = PropDef( 'names', 'QStringList', [], 'Names for the plot curves, ' 'defaults to the device names/keys.') legend = PropDef('legend', bool, False, 'If a legend should be shown.') plotwindow = PropDef( 'plotwindow', int, 3600, 'The range of time in ' 'seconds that should be represented by the plot.') plotinterval = PropDef( 'plotinterval', float, 2, 'The minimum time in ' 'seconds between two points that should be ' 'plotted.') height = PropDef( 'height', int, 10, 'Height of the plot widget in units ' 'of app font character width.') width = PropDef( 'width', int, 30, 'Width of the plot widget in units ' 'of app font character width.') # pylint: disable=W0231 def __init__(self, parent, designMode=False): self.ncurves = 0 self.ctimers = {} self.keyindices = {} self.plotcurves = {} self.series = {} self.legendobj = None # X label settings, default values for default window of 3600s self._showdate = False self._showsecs = False QWidget.__init__(self, parent) NicosWidget.__init__(self) def initUi(self): # axes setup self.widget = InteractiveGRWidget(self) self.plot = Plot(viewport=(.1, .95, .25, .95)) self.axes = NicosTimePlotAxes(self.plot._viewport) self.axes.setWindow(0, 1, 0, 1) self.plot.addAxes(self.axes) self.plot.setLegend(True) self.plot.setLegendWidth(0.07) self.plot.offsetXLabel = -.2 self.axes.setXtickCallback(self.xtickCallBack) self.widget.addPlot(self.plot) layout = QHBoxLayout(self) layout.addWidget(self.widget) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.curves = [] # event support self.widget.cbm.addHandler(LegendEvent.ROI_CLICKED, self.on_legendItemClicked, LegendEvent) self.widget.cbm.addHandler(MouseEvent.MOUSE_MOVE, self.on_mouseMove) self.timeSeriesUpdate.connect(self.on_timeSeriesUpdate) def xtickCallBack(self, x, y, _svalue, value): gr.setcharup(-1., 1.) gr.settextalign(gr.TEXT_HALIGN_RIGHT, gr.TEXT_VALIGN_TOP) dx = .02 timeVal = localtime(value) if self._showdate: gr.text(x + dx, y - 0.01, strftime(DATEFMT, timeVal)) if self._showsecs: gr.text(x - dx, y - 0.01, strftime(TIMEFMT, timeVal)) else: gr.text(x - dx, y - 0.01, strftime(SHORTTIMEFMT, timeVal)) gr.setcharup(0., 1.) def propertyUpdated(self, pname, value): if pname == 'plotwindow': self._showdate = value > 24 * 3600 self._showsecs = value < 300 elif pname in ('width', 'height'): self.setMinimumSize( QSize(self._scale * (self.props['width'] + .5), self._scale * (self.props['height'] + .5))) elif pname == 'legend': self.plot.setLegend(value) NicosWidget.propertyUpdated(self, pname, value) def setFont(self, font): pass # TODO: can't set font for GR right now def on_mouseMove(self, event): wc = event.getWC(self.plot.viewport) ts = strftime(DATEFMT + ' ' + TIMEFMT, localtime(wc.x)) msg = 't = %s, y = %g' % (ts, wc.y) self.widgetInfo.emit(msg) def on_legendItemClicked(self, event): if event.getButtons() & MouseEvent.LEFT_BUTTON: event.curve.visible = not event.curve.visible self.update() def on_timeSeriesUpdate(self, series): curve = self.plotcurves[series] curve.x = series.x curve.y = series.y c = self.axes.getCurves() dy = abs(c.ymin - c.ymax) * 0.05 self.axes.setWindow(c.xmin, c.xmax, c.ymin - dy, c.ymax + dy) self.widget.update() self.ctimers[curve].start(5000) def on_keyChange(self, key, value, time, expired): if key not in self.keyindices or value is None: return for index in self.keyindices[key]: series = self.series[key, index] # restrict time of value to 1 minute past at # maximum, so that it doesn't get culled by the windowing time = max(time, currenttime() - 60) if index: try: fvalue = functools.reduce(operator.getitem, index, value) series.add_value(time, fvalue) except Exception: pass else: series.add_value(time, value) def addcurve(self, key, index, title, scale, offset): series = TimeSeries(key, self.props['plotinterval'], scale, offset, self.props['plotwindow'], self) series.init_empty() curve = PlotCurve([currenttime()], [0], legend=title) self.plotcurves[series] = curve self.ncurves += 1 self.curves.append(curve) self.axes.addCurves(curve) self.series[key, index] = series self.widget.update() # record the current value at least every 5 seconds, to avoid curves # not updating if the value doesn't change def update(): series.synthesize_value() self.ctimers[curve] = QTimer(singleShot=True) self.ctimers[curve].timeout.connect(update) def registerKeys(self): for key, name in zip_longest(self.props['devices'], self.props['names']): if name is None: name = key key, index, scale, offset = extractKeyAndIndex(key) keyid = self._source.register(self, key) self.keyindices.setdefault(keyid, []).append(index) self.addcurve(keyid, index, name, scale, offset)
class NicosGrPlot(NicosPlot, InteractiveGRWidget): axescls = NicosPlotAxes HAS_AUTOSCALE = True SAVE_EXT = '.svg' def __init__(self, parent, window, timeaxis=False): InteractiveGRWidget.__init__(self, parent) NicosPlot.__init__(self, window, timeaxis=timeaxis) self.timeaxis = timeaxis or (self.axescls == NicosTimePlotAxes) self.leftTurnedLegend = True self.statusMessage = None self.mouselocation = None self._cursor = self.cursor() self._mouseSelEnabled = self.getMouseSelectionEnabled() self._markertype = gr.MARKERTYPE_OMARK dictPrintType = dict(gr.PRINT_TYPE) for prtype in [gr.PRINT_JPEG, gr.PRINT_TIF]: dictPrintType.pop(prtype) self._saveTypes = (";;".join(dictPrintType.values()) + ";;" + ";;".join(gr.GRAPHIC_TYPE.values())) self._saveName = None self._color = ColorIndexGenerator() self._plot = Plot(viewport=(.1, .85, .15, .88)) self._plot.setLegendWidth(0.05) self._axes = self.axescls(viewport=self._plot.viewport) self._axes.backgroundColor = 0 self._plot.addAxes(self._axes) self._plot.title = self.titleString() self.addPlot(self._plot) guiConn = GUIConnector(self) guiConn.connect(LegendEvent.ROI_CLICKED, self.on_legendItemClicked, LegendEvent) guiConn.connect(ROIEvent.ROI_CLICKED, self.on_roiItemClicked, ROIEvent) guiConn.connect(MouseEvent.MOUSE_PRESS, self.on_fitPicker_selected) guiConn.connect(MouseEvent.MOUSE_MOVE, self.on_mouseMove) self.logXinDomain.connect(self.on_logXinDomain) self.logYinDomain.connect(self.on_logYinDomain) self.setLegend(True) self.updateDisplay() def xtickCallBack(self, x, y, _svalue, value): gr.setcharup(-1. if self.leftTurnedLegend else 1., 1.) gr.settextalign( gr.TEXT_HALIGN_RIGHT if self.leftTurnedLegend else gr.TEXT_HALIGN_LEFT, gr.TEXT_VALIGN_TOP) dx = .015 timeVal = time.localtime(value) gr.text(x + (dx if self.leftTurnedLegend else -dx), y, time.strftime(DATEFMT, timeVal)) gr.text(x - (dx if self.leftTurnedLegend else -dx), y, time.strftime(TIMEFMT, timeVal)) gr.setcharup(0., 1.) def setAutoScaleFlags(self, xflag, yflag): mask = 0x0 if xflag: mask |= PlotAxes.SCALE_X if yflag: mask |= PlotAxes.SCALE_Y self.setAutoScale(mask) def setBackgroundColor(self, color): pass # not implemented def setFonts(self, font, bold, larger): pass # not implemented def updateDisplay(self): self._plot.title = self.titleString() if self.subTitleString(): self._plot.subTitle = self.subTitleString() self._plot.xlabel = self.xaxisName() self._plot.ylabel = self.yaxisName() if self.normalized: self._plot.ylabel += " (norm: %s)" % self.normalized self.plotcurves = [] self.addAllCurves() if self.timeaxis: self._plot.viewport = (.1, .85, .18, .88) self._axes.setXtickCallback(self.xtickCallBack) self._plot.offsetXLabel = -.08 scale = self.yaxisScale() if scale: axes = self._plot.getAxes(0) curwin = axes.getWindow() if not curwin: curwin = [0, 1, scale[0], scale[1]] curves = axes.getCurves() xmins = [] xmaxs = [] for c in curves: if c.visible: xmins.append(min(c.x)) xmaxs.append(max(c.x)) if xmins and xmaxs: curwin[0] = min(xmins) curwin[1] = max(xmaxs) axes.setWindow(curwin[0], curwin[1], scale[0], scale[1]) InteractiveGRWidget.update(self) def isLegendEnabled(self): return self._plot.isLegendEnabled() def setLegend(self, on): self._plot.setLegend(on) self.update() def isLogScaling(self, idx=0): axes = self._plot.getAxes(idx) return (axes.scale & gr.OPTION_Y_LOG if axes is not None else False) def isLogXScaling(self, idx=0): axes = self._plot.getAxes(idx) return (axes.scale & gr.OPTION_X_LOG if axes is not None else False) def setLogScale(self, on): self._plot.setLogY(on, rescale=True) self.update() def setLogXScale(self, on): self._plot.setLogX(on, rescale=True) self.update() def isErrorBarEnabled(self): axes = self._plot.getAxes(0) if axes: curves = axes.getCurves() if curves: return curves[0].isErrorBarEnabled(1) return False def setErrorBarEnabled(self, flag): for axis in self._plot.getAxes(): for curve in axis.getCurves(): curve.setErrorBarEnabled(flag) self.update() def setSymbols(self, on): markertype = self._markertype if on else gr.MARKERTYPE_DOT for axis in self._plot.getAxes(): for curve in axis.getCurves(): curve.markertype = markertype self.hasSymbols = on self.update() def setLines(self, on): linetype = None if on: linetype = gr.LINETYPE_SOLID for axis in self._plot.getAxes(): for curve in axis.getCurves(): curve.linetype = linetype self.hasLines = on self.update() def unzoom(self): self._plot.reset() self.update() def on_logXinDomain(self, flag): if not flag: self._plot.setLogX(flag) self.update() def on_logYinDomain(self, flag): if not flag: self.setLogScale(flag) def on_legendItemClicked(self, event): if event.getButtons() & MouseEvent.LEFT_BUTTON: event.curve.visible = not event.curve.visible if event.curve._parent: event.curve._parent.disabled = not event.curve._parent.disabled self.update() def on_roiItemClicked(self, event): if event.getButtons() & MouseEvent.RIGHT_BUTTON: if isinstance(event.roi.reference, FitResult): menu = QMenu(self) actionClipboard = QAction("Copy fit values to clipboard", menu) menu.addAction(actionClipboard) p0dc = event.getDC() selectedItem = menu.exec_( self.mapToGlobal(QPoint(p0dc.x, p0dc.y))) if selectedItem == actionClipboard: res = event.roi.reference text = '\n'.join( (n + '\t' if n else '\t') + (v + '\t' if isinstance(v, string_types) else '%g\t' % v) + (dv if isinstance(dv, string_types) else '%g' % dv) for (n, v, dv) in res.label_contents) QApplication.clipboard().setText(text) def on_mouseMove(self, event): if event.getWindow(): # inside plot self.mouselocation = event wc = event.getWC(self._plot.viewport) if self.statusMessage: msg = "%s (X = %g, Y = %g)" % (self.statusMessage, wc.x, wc.y) else: msg = "X = %g, Y = %g" % (wc.x, wc.y) self.window.statusBar.showMessage(msg) else: self.window.statusBar.clearMessage() def addPlotCurve(self, plotcurve, replot=False): existing_curve = next((c for c in self._axes.getCurves() if c._parent is plotcurve._parent), None) if existing_curve and not replot: existing_curve.visible = plotcurve.visible existing_curve.legend = plotcurve.legend existing_curve.setUpdateXCallback(None) existing_curve.setUpdateYCallback(None) # update curve existing_curve.x, existing_curve.y = plotcurve.x, plotcurve.y if plotcurve.errorBar1 and existing_curve.errorBar1: mcolor = existing_curve.errorBar1.markercolor existing_curve.errorBar1 = plotcurve.errorBar1 existing_curve.errorBar1.markercolor = mcolor else: existing_curve.errorBar1 = plotcurve.errorBar1 if plotcurve.errorBar2 and existing_curve.errorBar2: mcolor = existing_curve.errorBar2.markercolor existing_curve.errorBar2 = plotcurve.errorBar2 existing_curve.errorBar2.markercolor = mcolor else: existing_curve.errorBar2 = plotcurve.errorBar2 if existing_curve not in self.plotcurves: self.plotcurves.append(existing_curve) else: color = self._color.getNextColorIndex() plotcurve.linecolor = color plotcurve.markercolor = color plotcurve.markertype = self._markertype if self.hasSymbols \ else gr.MARKERTYPE_DOT if plotcurve.errorBar1: plotcurve.errorBar1.markercolor = color if plotcurve.errorBar2: plotcurve.errorBar2.markercolor = color self._axes.addCurves(plotcurve) self.plotcurves.append(plotcurve) def savePlot(self): saveName = None dialog = QFileDialog(self, "Select file name", "", self._saveTypes) dialog.selectNameFilter(gr.PRINT_TYPE[gr.PRINT_PDF]) dialog.setOption(dialog.HideNameFilterDetails, False) dialog.setAcceptMode(QFileDialog.AcceptSave) if dialog.exec_() == QDialog.Accepted: path = dialog.selectedFiles()[0] if path: _p, suffix = os.path.splitext(path) if suffix: suffix = suffix.lower() else: # append selected name filter suffix (filename extension) nameFilter = dialog.selectedNameFilter() for k, v in gr.PRINT_TYPE.items(): if v == nameFilter: suffix = '.' + k path += suffix break if suffix and (suffix[1:] in gr.PRINT_TYPE or suffix[1:] in gr.GRAPHIC_TYPE): self.save(path) saveName = os.path.basename(path) self._saveName = saveName else: raise Exception("Unsupported file format") return saveName def printPlot(self): self.printDialog("Nicos-" + self._saveName if self._saveName else "untitled") return True @property def plot(self): """Get current gr.pygr.Plot object.""" return self._plot def _save(self, extension=".pdf"): fd, pathname = tempfile.mkstemp(extension) self.save(pathname) os.close(fd) return pathname def saveQuietly(self): return self._save(".svg") def _getCurveData(self, curve): errBar1 = curve.errorBar1 return [curve.x, curve.y, errBar1.dpos if errBar1 else None] def _getCurveLegend(self, curve): return curve.legend def _isCurveVisible(self, curve): return curve.visible def setVisibility(self, item, on): item.visible = on if item._parent: item._parent.disabled = not on def _enterFitMode(self): self.window.statusBar.showMessage(self.statusMessage) self._cursor = self.cursor() self.setCursor(QCursor(Qt.CrossCursor)) self._mouseSelEnabled = self.getMouseSelectionEnabled() self.setMouseSelectionEnabled(False) def _fitRequestPick(self, paramname): self.statusMessage = 'Fitting: Click on %s' % paramname self.window.statusBar.showMessage(self.statusMessage) def _leaveFitMode(self): self.fitter = None self.statusMessage = None self.setCursor(self._cursor) self.setMouseSelectionEnabled(self._mouseSelEnabled) def _plotFit(self, res): color = self._color.getNextColorIndex() resultcurve = NicosPlotCurve(res.curve_x, res.curve_y, legend=res._title, linecolor=color, markercolor=color) self.addPlotCurve(resultcurve, True) resultcurve.markertype = gr.MARKERTYPE_DOT self.window.statusBar.showMessage("Fitting complete") text = '\n'.join( (n + ': ' if n else '') + (v if isinstance(v, string_types) else '%g' % v) + (dv if isinstance(dv, string_types) else ' +/- %g' % dv) for (n, v, dv) in res.label_contents) grtext = Text(res.label_x, res.label_y, text, self._axes, .012, hideviewport=False) resultcurve.dependent.append(grtext) coord = CoordConverter(self._axes.sizex, self._axes.sizey, self._axes.getWindow()) roi = RegionOfInterest(reference=res, regionType=RegionOfInterest.TEXT, axes=self._axes) for nxi, nyi in zip(*grtext.getBoundingBox()): coord.setNDC(nxi, nyi) roi.append(coord.getWC(self._axes.viewport)) self._plot.addROI(roi) self.update() def on_fitPicker_selected(self, point): if self.fitter and point.getButtons() & MouseEvent.LEFT_BUTTON and \ point.getWindow(): p = point.getWC(self._plot.viewport) self.fitter.addPick((p.x, p.y)) def _modifyCurve(self, curve, op): new_y = [ eval(op, { 'x': v1, 'y': v2 }) for (v1, v2) in zip(curve.x, curve.y) ] if curve.errorBar1: curve.errorBar1.y = new_y if curve.errorBar2: curve.errorBar2.y = new_y curve.y = new_y def setMarkerType(self, markertype): self._markertype = markertype
# -*- coding: utf-8 -*- """ Draw text at an arbitrary position on the Axes using gr.pygr. """ # local library import gr from gr.pygr import Plot, PlotAxes, PlotCurve, Text if __name__ == "__main__": tx, ty = 0, -20 x = [-3.3 + t * 0.1 for t in range(66)] y = [t ** 5 - 13 * t ** 3 + 36 * t for t in x] txtfmt = "Text drawn on\n(%g, %g) with\nhalign left, valign top" plt = Plot((0.1, 0.95, 0.1, 0.88)) plt.title = "Text on Axes Example" plt.subTitle = "Show usage of gr.pygr.Text" plt.xlabel = "x" plt.ylabel = "y" curve = PlotCurve(x, y, legend="foo bar") axes = PlotAxes(plt.viewport).addCurves(curve) axes.setWindow(-4.0, 4.0, -60.0, 40.0) text = Text(tx, -ty, txtfmt % (tx, -ty), axes, 0.02) plt.addAxes(axes) text2 = Text(tx, ty, txtfmt % (tx, ty), axes, 0.02) tbx, tby = text2.getBoundingBox() plt.drawGR() text.drawGR()