本文整理汇总了Python中pyqtgraph.PlotWidget.addLegend方法的典型用法代码示例。如果您正苦于以下问题:Python PlotWidget.addLegend方法的具体用法?Python PlotWidget.addLegend怎么用?Python PlotWidget.addLegend使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyqtgraph.PlotWidget
的用法示例。
在下文中一共展示了PlotWidget.addLegend方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RealtimePlotWidget
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addLegend [as 别名]
class RealtimePlotWidget(QWidget):
COLORS = [Qt.red, Qt.blue, Qt.green, Qt.magenta, Qt.cyan,
Qt.darkRed, Qt.darkBlue, Qt.darkGreen, Qt.darkYellow, Qt.gray]
def __init__(self, parent=None):
super(RealtimePlotWidget, self).__init__(parent)
self._plot_widget = PlotWidget()
self._plot_widget.setBackground((0, 0, 0))
self._plot_widget.addLegend()
self._plot_widget.showButtons()
self._plot_widget.enableAutoRange()
self._plot_widget.showGrid(x=True, y=True, alpha=0.2)
vbox = QVBoxLayout()
vbox.addWidget(self._plot_widget)
self.setLayout(vbox)
self._color_index = 0
self._curves = {}
def add_curve(self, curve_id, curve_name, data_x=[], data_y=[]):
color = QColor(self.COLORS[self._color_index % len(self.COLORS)])
self._color_index += 1
pen = mkPen(color, width=1)
plot = self._plot_widget.plot(name=curve_name, pen=pen)
data_x = numpy.array(data_x)
data_y = numpy.array(data_y)
self._curves[curve_id] = {'x': data_x, 'y': data_y, 'plot': plot}
def remove_curve(self, curve_id):
curve_id = str(curve_id)
if curve_id in self._curves:
self._plot_widget.removeItem(self._curves[curve_id]['plot'])
del self._curves[curve_id]
def set_x_range(self, left, right):
self._plot_widget.setRange(xRange=(left, right))
def update_values(self, curve_id, x, y):
curve = self._curves[curve_id]
curve['x'] = numpy.append(curve['x'], x)
curve['y'] = numpy.append(curve['y'], y)
def redraw(self):
for curve in self._curves.values():
if len(curve['x']):
curve['plot'].setData(curve['x'], curve['y'])
def lazy_redraw(self, period):
timestamp = time.time()
if not hasattr(self, '_prev_lazy_redraw'):
self._prev_lazy_redraw = 0.0
if timestamp - self._prev_lazy_redraw > period:
self._prev_lazy_redraw = timestamp
self.redraw()
示例2: __init__
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addLegend [as 别名]
def __init__(self, instance):
super(GUIBuilder, self).__init__()
self.setCentralWidget(QWidget())
layout = QVBoxLayout(self.centralWidget())
self.plots_layout = DockArea()
layout.addWidget(self.plots_layout)
self.form_layout = QFormLayout()
self.form_layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
layout.addLayout(self.form_layout)
self.buttons_layout = QHBoxLayout()
layout.addLayout(self.buttons_layout)
self.instance = instance
self.plot_widgets = {}
self.plot_data_items = {}
self.plot_color_generators = {}
seen_form_items = []
seen_plot_items = []
for node in ast.walk(ast.parse(getsource(type(instance)))):
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
if node.func.id.startswith('gb_get_') or node.func.id.startswith('gb_set_'):
segs = node.func.id.split('_')
caster = __builtins__[segs[2]]
name = "_".join(segs[3:])
if name in seen_form_items:
continue
seen_form_items.append(name)
if caster is bool:
editor = QCheckBox()
if node.func.id.startswith('gb_get_') and node.args:
editor.setChecked(node.args[0].id == 'True')
get_fn = lambda e=editor: e.isChecked()
set_fn = lambda v, e=editor: e.setChecked(v)
else:
editor = QLineEdit()
if node.func.id.startswith('gb_get_') and node.args:
if isinstance(node.args[0], ast.Num):
init = node.args[0].n
else:
init = node.args[0].s
editor.setText(str(caster(init)))
get_fn = lambda e=editor, c=caster: c(e.text())
set_fn = lambda val, e=editor: e.setText(str(val))
base_name = "_".join(segs[2:])
get_name = "gb_get_" + base_name
set_name = "gb_set_" + base_name
__builtins__[get_name] = lambda init=0, get_fn=get_fn: get_fn()
__builtins__[set_name] = lambda val, set_fn=set_fn: set_fn(val)
self.form_layout.addRow(prettify(name), editor)
if node.func.id.startswith('gb_plot_'):
segs = node.func.id.split("_")
plot_type = segs[2]
plot_name = segs[3]
if len(segs) >= 5:
data_item_name = "_".join(segs[4:])
else:
data_item_name = ""
if (plot_name, data_item_name) in seen_plot_items:
continue
seen_plot_items.append((plot_name, data_item_name))
if plot_name not in self.plot_widgets:
if plot_type in ['y', 'xy']:
pw = PlotWidget()
self.plot_widgets[plot_name] = pw
self.plot_color_generators[plot_name] = itertools.cycle('rgb')
pw.addLegend()
else:
raise ValueError("Unknown plot type in {}: {}".format(node.func.id, plot_type))
dock = Dock(name=prettify(plot_name), widget=pw)
self.plots_layout.addDock(dock, 'above')
self.add_plot_item(node.func.id, plot_name, data_item_name)
if isinstance(node, ast.FunctionDef):
if node.name.endswith("_gb_button"):
name = "_".join(node.name.split("_")[:-2])
button = QPushButton(prettify(name))
button.clicked.connect(getattr(instance, node.name))
self.buttons_layout.addWidget(button)
示例3: QGraph
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addLegend [as 别名]
class QGraph(QWidget):
def __init__(self, config, parent=None, **kwargs):
QWidget.__init__(self, parent)
self.startTime = None
self.numDataPoints = 0
self.datasets = {}
for display in config['displays']:
self.datasets[display['field']] = self.createDatasetForDisplay(display)
self.graph = PlotWidget(title=config['title'], labels=config['labels'])
# Only add a legend to the graph if there is more than one dataset displayed on it
if len(self.datasets) > 1:
self.graph.addLegend()
# Show grid lines
self.graph.showGrid(x=True, y=True)
for _, dataset in self.datasets.items():
self.graph.addItem(dataset['plotData'])
vbox = QVBoxLayout()
vbox.addWidget(self.graph)
self.setLayout(vbox)
def createDatasetForDisplay(self, display):
plotData = PlotDataItem(name=display['label'])
if 'color' in display:
plotData.setPen(mkPen({'color': display['color']}))
return {
'plotData': plotData,
'points': numpy.zeros((constants.NUMPY_ARRAY_SIZE, 2)),
}
def updateDataset(self, dataset):
time = self.getAxisTime(dataset)
# Skip updating if no time is available
if not time:
return
for field, _ in self.datasets.items():
self.updatePoints(time, field, dataset)
self.updateGraphs(field, dataset)
self.numDataPoints += 1
def updatePoints(self, time, field, dataset):
for key, data in dataset.items():
# Only plot float values
if field == key and isinstance(data, float):
self.datasets[field]['points'][self.numDataPoints] = (time, data)
return
def getAxisTime(self, dataset):
# Use the first dataset as the start time
if not self.startTime and dataset['delta']:
self.startTime = dataset['delta']
if dataset['delta']:
return (dataset['delta'] - self.startTime)
else:
return None
def updateGraphs(self, field, dataset):
for data in dataset.items():
if field in dataset:
# We don't want to graph the empty values in the points array so only
# give the plot data the points up to the current number of data points
points = self.datasets[field]['points']
self.datasets[field]['plotData'].setData(points[0:self.numDataPoints])
示例4: init_widget
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addLegend [as 别名]
def init_widget(self):
layout = QtGui.QHBoxLayout()
self.setLayout(layout)
plot_layout = QtGui.QHBoxLayout()
layout.addLayout(plot_layout)
plots = {}
traces = {}
for plot in PLOTS:
plot_dict = PLOTS_DICT[plot]
plot_widget = PlotWidget(
title=plot_dict[TITLE],
labels={
'bottom':'time (samples)',
'left':plot_dict[LABEL]
}
)
plot_traces = plot_dict[TRACES]
if len(plot_traces) > 1:
plot_widget.addLegend()
trace_index = 0
colors = ('F33','3F3','33F')
for trace_key, trace_d in plot_traces.items():
trace = [0] * HISTORY
kwargs = {
LINE:{
'pen':{'color':colors[trace_index]}
},
SCATTER:{
'pen':None,
'symbol':'o',
'symbolSize':3,
'symbolBrush':colors[trace_index]
}
}[trace_d[TRACE_TYPE]]
kwargs['name'] = trace_d[TRACE_NAME]
plot = plot_widget.plot(
trace,
**kwargs
)
plots[trace_key] = plot
traces[trace_key] = trace
trace_index += 1
plot_layout.addWidget(plot_widget)
client = yield connectAsync()
sh_server = client.sample_heater
controls_layout = QtGui.QVBoxLayout()
layout.addLayout(controls_layout)
temperature_setpoint_layout = QtGui.QHBoxLayout()
controls_layout.addWidget(
LabelWidget(
'temperature setpoint',
temperature_setpoint_layout
)
)
temperature_setpoint_label = QtGui.QLabel()
temperature_setpoint_layout.addWidget(temperature_setpoint_label)
temperature_setpoint_layout.addStretch()
temperature_setpoint_spin = QtGui.QSpinBox()
temperature_setpoint_spin.setRange(MIN_TEMPERATURE,MAX_TEMPERATURE)
temperature_setpoint_spin.setPrefix('temp')
temperature_setpoint_spin.setSuffix('C')
temperature_setpoint_layout.addWidget(temperature_setpoint_spin)
temperature_setpoint_button = QtGui.QPushButton('set')
temperature_setpoint_layout.addWidget(temperature_setpoint_button)
def set_temperature_setpoint():
catch_labrad_error(
self,
sh_server.set_temperature_setpoint(temperature_setpoint_spin.value())
)
temperature_setpoint_button.clicked.connect(set_temperature_setpoint)
def update_temperature_setpoint(temperature_setpoint):
self.temperature_setpoint = temperature_setpoint
temperature_setpoint_label.setText('temp setpoint: %d' % self.temperature_setpoint)
sh_server.on_temperature_setpoint_changed.connect(
lambda c, temperature_setpoint: update_temperature_setpoint(temperature_setpoint)
)
temperature_setpoint = yield sh_server.get_temperature_setpoint()
update_temperature_setpoint(temperature_setpoint)
def update_label(label,state):
label.setText('status: ' + str(state))
for name, signal, getter, setter, option_1, option_2 in (
(
'heating state',
sh_server.on_heating_state_changed,
sh_server.get_heating_state,
#.........这里部分代码省略.........
示例5: Plotter
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addLegend [as 别名]
class Plotter(QWidget):
MAX_DATA_POINTS_PER_CURVE = 200000
COLORS = [Qt.red, Qt.green, Qt.blue, # RGB - http://ux.stackexchange.com/questions/79561
Qt.yellow, Qt.cyan, Qt.magenta, # Close to RGB
Qt.darkRed, Qt.darkGreen, Qt.darkBlue, # Darker RGB
Qt.darkYellow, Qt.darkCyan, Qt.darkMagenta, # Close to RGB
Qt.gray, Qt.darkGray] # Leftovers
INITIAL_X_RANGE = 60
def __init__(self, parent=None):
# Parent
super(Plotter, self).__init__(parent)
self.setWindowTitle('UAVCAN Plotter')
self.setWindowIcon(APP_ICON)
# Redraw timer
self._update_timer = QTimer()
self._update_timer.timeout.connect(self._update)
self._update_timer.setSingleShot(False)
self._update_timer.start(30)
# PyQtGraph
self._plot_widget = PlotWidget()
self._plot_widget.setBackground((0, 0, 0))
self._legend = self._plot_widget.addLegend()
self._plot_widget.setRange(xRange=(0, self.INITIAL_X_RANGE), padding=0)
self._plot_widget.showButtons()
self._plot_widget.enableAutoRange()
self._plot_widget.showGrid(x=True, y=True, alpha=0.4)
# Controls
# https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
button_add_matcher = QtGui.QPushButton('New matcher', self)
button_add_matcher.setIcon(QtGui.QIcon.fromTheme('list-add'))
button_add_matcher.setToolTip('Add new curve matcher')
button_add_matcher.clicked.connect(
lambda: NewCurveMatcherWindow(self, lambda: sorted(self._active_messages), self._add_curve_matcher).show())
button_clear_plots = QtGui.QPushButton('Clear plots', self)
button_clear_plots.setIcon(QtGui.QIcon.fromTheme('edit-clear'))
button_clear_plots.setToolTip('Clear the plotting area')
button_clear_plots.clicked.connect(lambda: self._remove_all_curves())
def delete_all_matchers():
self._curve_matchers = []
for i in reversed(range(self._curve_matcher_container.count())):
self._curve_matcher_container.itemAt(i).widget().deleteLater()
self._remove_all_curves()
button_delete_all_matchers = QtGui.QPushButton('Delete matchers', self)
button_delete_all_matchers.setIcon(QtGui.QIcon.fromTheme('edit-delete'))
button_delete_all_matchers.setToolTip('Delete all matchers')
button_delete_all_matchers.clicked.connect(delete_all_matchers)
self._autoscroll = QtGui.QCheckBox('Autoscroll', self)
self._autoscroll.setChecked(True)
self._max_x = self.INITIAL_X_RANGE
# Layout
control_panel = QHBoxLayout()
control_panel.addWidget(button_add_matcher)
control_panel.addWidget(button_clear_plots)
control_panel.addWidget(self._autoscroll)
control_panel.addStretch()
control_panel.addWidget(button_delete_all_matchers)
self._curve_matcher_container = QVBoxLayout()
layout = QVBoxLayout()
layout.addWidget(self._plot_widget, 1)
layout.addLayout(control_panel)
layout.addLayout(self._curve_matcher_container)
self.setLayout(layout)
# Logic
self._color_index = 0
self._curves = {}
self._message_queue = multiprocessing.Queue()
self._active_messages = set() # set(data type name)
self._curve_matchers = []
# Defaults
self._add_curve_matcher(CurveMatcher('uavcan.protocol.debug.KeyValue', 'value', [('key', None)]))
def _add_curve_matcher(self, matcher):
self._curve_matchers.append(matcher)
view = CurveMatcherView(matcher, self)
def remove():
self._curve_matchers.remove(matcher)
self._curve_matcher_container.removeWidget(view)
view.setParent(None)
view.deleteLater()
view.on_remove = remove
self._curve_matcher_container.addWidget(view)
def _update(self):
#.........这里部分代码省略.........
示例6: RealtimePlotWidget
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addLegend [as 别名]
class RealtimePlotWidget(QWidget):
AUTO_RANGE_FRACTION = 0.99
COLORS = [Qt.red, Qt.blue, Qt.green, Qt.magenta, Qt.cyan,
Qt.darkRed, Qt.darkBlue, Qt.darkGreen, Qt.darkYellow, Qt.gray]
def __init__(self, display_measurements, parent):
super(RealtimePlotWidget, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose) # This is required to stop background timers!
self._plot_widget = PlotWidget()
self._plot_widget.setBackground((0, 0, 0))
self._legend = self._plot_widget.addLegend()
self._plot_widget.showButtons()
self._plot_widget.showGrid(x=True, y=True, alpha=0.3)
vbox = QVBoxLayout(self)
vbox.addWidget(self._plot_widget)
self.setLayout(vbox)
self._last_update_ts = 0
self._reset_required = False
self._update_timer = QTimer(self)
self._update_timer.setSingleShot(False)
self._update_timer.timeout.connect(self._update)
self._update_timer.start(200)
self._color_index = 0
self._curves = {}
# Crosshair
def _render_measurements(cur, ref):
text = 'time %.6f sec, y %.6f' % cur
if ref is None:
return text
dt = cur[0] - ref[0]
dy = cur[1] - ref[1]
if abs(dt) > 1e-12:
freq = '%.6f' % abs(1 / dt)
else:
freq = 'inf'
display_measurements(text + ';' + ' ' * 4 + 'dt %.6f sec, freq %s Hz, dy %.6f' % (dt, freq, dy))
display_measurements('Hover to sample Time/Y, click to set new reference')
add_crosshair(self._plot_widget, _render_measurements)
# Final reset
self.reset()
def _trigger_auto_reset_if_needed(self):
ts = time.monotonic()
dt = ts - self._last_update_ts
self._last_update_ts = ts
if dt > 2:
self._reset_required = True
def add_curve(self, curve_id, curve_name, data_x=[], data_y=[]):
color = QColor(self.COLORS[self._color_index % len(self.COLORS)])
self._color_index += 1
pen = mkPen(color, width=1)
plot = self._plot_widget.plot(name=curve_name, pen=pen)
data_x = numpy.array(data_x)
data_y = numpy.array(data_y)
self._curves[curve_id] = {'data': (data_x, data_y), 'plot': plot}
self._trigger_auto_reset_if_needed()
def update_values(self, curve_id, x, y):
curve = self._curves[curve_id]
old_x, old_y = curve['data']
curve['data'] = numpy.append(old_x, x), numpy.append(old_y, y)
self._trigger_auto_reset_if_needed()
def reset(self):
for curve in self._curves.keys():
self._plot_widget.removeItem(self._curves[curve]['plot'])
self._curves = {}
self._color_index = 0
self._plot_widget.enableAutoRange(enable=self.AUTO_RANGE_FRACTION,
x=self.AUTO_RANGE_FRACTION,
y=self.AUTO_RANGE_FRACTION)
self._legend.scene().removeItem(self._legend)
self._legend = self._plot_widget.addLegend()
def _update(self):
if self._reset_required:
self.reset()
self._reset_required = False
for curve in self._curves.values():
if len(curve['data'][0]):
curve['plot'].setData(*curve['data'])