def plot(self, *args, **kwargs): plot = Plot() axes = PlotAxes(plot.viewport) axes.plot(*args, **kwargs) plot.addAxes(axes) return self.addPlot(plot)
class MainWindow(QtWidgets.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 if sys.version_info[0] == 2: self._title = unicode(self.windowTitle()) else: self._title = str(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._actionAboutQt.triggered.connect( lambda: QtWidgets.QMessageBox.aboutQt(self)) self._gr.logXinDomain.connect(self._logXinDomain) self._gr.logYinDomain.connect(self._logYinDomain) self._gr.modePick.connect(self._pickModeChanged) self._gr.cbm.addHandler(MouseEvent.MOUSE_MOVE, self.mouseMoveGr) self._gr.cbm.addHandler(PickEvent.PICK_PRESS, self.pointPickGr) self._gr.cbm.addHandler(LegendEvent.ROI_CLICKED, self.legendClick) self._gr.cbm.addHandler(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 derr = [0.25 * abs(yi) for yi in y] self._errBar = ErrorBar(x, y, derr) self._plot = Plot((.1, .92, .2, .88)) self._plot.offsetXLabel = -.1 self._curveFoo = PlotCurve(x, y, legend="foo bar") axes = PlotAxes(self._plot.viewport).addCurves(self._curveFoo) axes.setXtickCallback(self._xtickCallBack) self._plot.addAxes(axes, PlotAxes(self._plot.viewport, drawX=False).plot(x2, y2)) self._plot2 = Plot((.1, .95, .15, .88)) self._plot2.addAxes(PlotAxes(self._plot2.viewport).addCurves( PlotCurve(x2, y2, legend="second"))) self._plot.title = "QtGR Demo (%s)" % backend 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 = QtWidgets.QFileDialog.getSaveFileName(self, "", "", self._saveTypes, gr.PRINT_TYPE[gr.PRINT_PDF]) if qpath: if sys.version_info[0] == 2: path = unicode(qpath) else: path = str(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, value): gr.setcharup(1., 1.) gr.settextalign(gr.TEXT_HALIGN_LEFT, gr.TEXT_VALIGN_TOP) gr.text(x, y, "%s (%s)" % (time.strftime("%H:%M:%S", time.localtime(self._startupTime + value)), 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) 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)
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
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() # set viewport and window accordingly to draw in NDC space gr.setviewport(0, axes.sizex, 0, axes.sizey) gr.setwindow(0, axes.sizex, 0, axes.sizey) gr.fillarea(tbx, tby) gr.updatews()
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 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 if sys.version_info[0] == 2: self._title = unicode(self.windowTitle()) else: self._title = str(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 * 0.1 for t in range(66)] y = [t ** 5 - 13 * t ** 3 + 36 * t for t in x] x2 = [-3.5 + i * 0.5 for i in range(0, 15)] y2 = x2 derr = [0.25 * abs(yi) for yi in y] self._errBar = ErrorBar(x, y, derr) self._plot = Plot((0.1, 0.92, 0.2, 0.88)) self._plot.offsetXLabel = -0.1 self._curveFoo = PlotCurve(x, y, legend="foo bar") axes = PlotAxes(self._plot.viewport).addCurves(self._curveFoo) axes.setXtickCallback(self._xtickCallBack) self._plot.addAxes(axes, PlotAxes(self._plot.viewport, drawX=False).plot(x2, y2)) self._plot2 = Plot((0.1, 0.95, 0.15, 0.88)) self._plot2.addAxes(PlotAxes(self._plot2.viewport).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: if sys.version_info[0] == 2: path = unicode(qpath) else: path = str(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, value): gr.setcharup(1.0, 1.0) gr.settextalign(gr.TEXT_HALIGN_LEFT, gr.TEXT_VALIGN_TOP) gr.text(x, y, "%s (%s)" % (time.strftime("%H:%M:%S", time.localtime(self._startupTime + value)), svalue)) gr.setcharup(0.0, 1.0) 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)
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() text2.drawGR() # set viewport and window accordingly to draw in NDC space gr.setviewport(0, axes.sizex, 0, axes.sizey) gr.setwindow(0, axes.sizex, 0, axes.sizey) gr.fillarea(tbx, tby)