本文整理汇总了Python中pyqtgraph.PlotWidget.addItem方法的典型用法代码示例。如果您正苦于以下问题:Python PlotWidget.addItem方法的具体用法?Python PlotWidget.addItem怎么用?Python PlotWidget.addItem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyqtgraph.PlotWidget
的用法示例。
在下文中一共展示了PlotWidget.addItem方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PyQtGraphDataPlot
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addItem [as 别名]
class PyQtGraphDataPlot(QWidget):
limits_changed = Signal()
def __init__(self, parent=None):
super(PyQtGraphDataPlot, self).__init__(parent)
self._plot_widget = PlotWidget()
self._plot_widget.getPlotItem().addLegend()
self._plot_widget.setBackground((255, 255, 255))
self._plot_widget.setXRange(0, 10, padding=0)
vbox = QVBoxLayout()
vbox.addWidget(self._plot_widget)
self.setLayout(vbox)
self._plot_widget.getPlotItem().sigRangeChanged.connect(self.limits_changed)
self._curves = {}
self._current_vline = None
def add_curve(self, curve_id, curve_name, curve_color=QColor(Qt.blue), markers_on=False):
pen = mkPen(curve_color, width=1)
symbol = "o"
symbolPen = mkPen(QColor(Qt.black))
symbolBrush = mkBrush(curve_color)
# this adds the item to the plot and legend
if markers_on:
plot = self._plot_widget.plot(name=curve_name, pen=pen, symbol=symbol, symbolPen=symbolPen, symbolBrush=symbolBrush, symbolSize=4)
else:
plot = self._plot_widget.plot(name=curve_name, pen=pen)
self._curves[curve_id] = 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])
del self._curves[curve_id]
self._update_legend()
def _update_legend(self):
# clear and rebuild legend (there is no remove item method for the legend...)
self._plot_widget.clear()
self._plot_widget.getPlotItem().legend.items = []
for curve in self._curves.values():
self._plot_widget.addItem(curve)
if self._current_vline:
self._plot_widget.addItem(self._current_vline)
def redraw(self):
pass
def set_values(self, curve_id, data_x, data_y):
curve = self._curves[curve_id]
curve.setData(data_x, data_y)
def vline(self, x, color):
if self._current_vline:
self._plot_widget.removeItem(self._current_vline)
self._current_vline = self._plot_widget.addLine(x=x, pen=color)
def set_xlim(self, limits):
# TODO: this doesn't seem to handle fast updates well
self._plot_widget.setXRange(limits[0], limits[1], padding=0)
def set_ylim(self, limits):
self._plot_widget.setYRange(limits[0], limits[1], padding=0)
def get_xlim(self):
x_range, _ = self._plot_widget.viewRange()
return x_range
def get_ylim(self):
_, y_range = self._plot_widget.viewRange()
return y_range
示例2: Tiare
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addItem [as 别名]
#.........这里部分代码省略.........
self.fig_energy = PlotWidget(self.widget, background="w")
self.fig_energy.setXLink(self.fig_signal)
self.fig_segments = PlotWidget(self.widget, background="w")
self.fig_segments.setXLink(self.fig_signal)
self.fig_segments.hideAxis('bottom')
self.fig_segments.hideAxis('left')
self.fig_segments.setLimits(yMin=-1, yMax=1, minYRange=2, maxYRange=2)
self.sizer.addWidget(self.fig_signal, 5)
self.sizer.addWidget(self.fig_energy, 5)
self.sizer.addWidget(self.fig_segments, 3)
self.sizer.addWidget(QtGui.QLabel('Seuil de segmentation'), 0)
self.sizer.addWidget(self.th_slider, 0)
self.min_seg_label = QtGui.QLabel('Longeur minimal de segment (%.3f s)' % (float(self.min_len.value())/100))
self.sizer.addWidget(self.min_seg_label, 0)
self.sizer.addWidget(self.min_len, 0)
self.min_sil_label = QtGui.QLabel('Longeur minimal de silence (%.3f s)' % (float(self.min_len_sil.value())/100))
self.sizer.addWidget(self.min_sil_label, 0)
self.sizer.addWidget(self.min_len_sil, 0)
# Apply sizers
self.setCentralWidget(self.widget)
# Finish
self.resize(560, 420)
self.setWindowTitle('Tiare')
self.energy_tl, self.energy = [], []
self.thline = None
self.seg_up = None
self.seg_down = None
self.fig_energy_plot = None
self.segments = []
self.samples = []
self.sr = 0
self.filepath = None
self.widget.hide()
self.show()
def change_threshold(self, value):
value = float(value)/100
if self.thline is not None :
self.thline.setData([self.energy_tl[0], self.energy_tl[-1]], [value]*2)
self.segments = map(lambda (x, y): (self.energy_tl[x],self.energy_tl[y]),
cut(self.energy, value, self.min_len.value(), self.min_len_sil.value()))
x = [v for start, stop in self.segments for v in [start, start, stop, stop]]
y = [v for _ in self.segments for v in [-0.85, 0.85, 0.85, -0.85]]
self.seg_up.setData(x, y)
self.seg_down.setData([self.energy_tl[0], self.energy_tl[-1]], [-0.85, -0.85])
def change_min_len(self, value=0):
self.min_seg_label.setText("Longeur minimale d'un segment (%.3f s)" % (float(self.min_len.value())/100))
self.min_sil_label.setText("Longeur minimale d'un silence (%.3f s)" % (float(self.min_len_sil.value())/100))
self.change_threshold(self.th_slider.value())
def compute_energy(self, value=None):
self.energy_tl, self.energy = energy(self.samples, self.sr)
if self.fig_energy_plot is not None:
self.fig_energy_plot.setData(self.energy_tl, self.energy)
self.change_min_len()
def export(self):
fpath = QtGui.QFileDialog.getSaveFileName(self, "Sauvegader en CSV", self.filepath+".csv")
if fpath:
with open(fpath[0], "w") as f:
for start, stop in self.segments:
f.write("Segments\t%s\t%s\n" % (datetime(day=1, month=1, year=1901, second=int(start),
microsecond=int(10e5*(start % 1)))
.strftime("%H:%M:%S.%f"),
datetime(day=1, month=1, year=1901, second=int(stop),
microsecond=int(10e5*(stop % 1)))
.strftime("%H:%M:%S.%f")))
def load(self):
fpath, _ = QtGui.QFileDialog.getOpenFileName(self, 'Choisir un fichier', '~/', filter="*.wav")
self.widget.show()
if fpath:
self.filepath = fpath
self.saveAction.setEnabled(True)
self.samples, self.sr = load_sound(fpath)
m = max(map(abs, self.samples))
timeline = [float(t)/self.sr for t in range(len(self.samples))]
self.fig_signal.setLimits(xMax=timeline[-1])
self.compute_energy()
self.fig_signal.getPlotItem().plot(timeline, map(lambda x: x/m, self.samples))
self.fig_energy_plot = self.fig_energy.getPlotItem().plot(self.energy_tl, self.energy)
self.thline = self.fig_energy.getPlotItem().plot([self.energy_tl[0], self.energy_tl[-1]],
[float(self.th_slider.value())/100]*2,
pen=({'color': "k", "width": 1.5}))
self.seg_up = self.fig_segments.getPlotItem().plot([self.energy_tl[0], self.energy_tl[-1]],
[-0.85, -0.85])
self.seg_down = self.fig_segments.getPlotItem().plot([self.energy_tl[0], self.energy_tl[-1]],
[-0.85, -0.85])
self.segments = FillBetweenItem(self.seg_up, self.seg_down, 0.7)
self.fig_segments.addItem(self.segments)
示例3: SpectrometerWidget
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addItem [as 别名]
class SpectrometerWidget(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setLayout(QtGui.QHBoxLayout())
self.resize(700, 500)
self.wave = []
self.spec = []
self.time = None
@inlineCallbacks
def onInit():
# connect to server
ipAddress = TEST_SPECTROMETER_SERVER if DEBUG else SPECTROMETER_SERVER
protocol = yield getProtocol(ipAddress)
# create a client
self.client = SpectrometerClient(protocol)
self.wave = yield self.client.getWavelengths()
self.numberToAverage = 1
self.numberAcquired = 0
self.darkSpectrum = np.zeros(NUM_PIXELS)
self.specProcessed = np.zeros(NUM_PIXELS)
self.gettingDark = False
# set up overall layout: 1 large panel (plot) to left of 1 narrow /
# panel (controls) all above 1 skinny panel (timestamp)
fullLayout = QtGui.QVBoxLayout()
self.layout().addLayout(fullLayout)
topHalfLayout = QtGui.QHBoxLayout()
fullLayout.addLayout(topHalfLayout)
# define the plot
self.plotWidget = PlotWidget()
self.plot = self.plotWidget.plot()
topHalfLayout.addWidget(self.plotWidget, 1)
# define the controls panel
cpLayout = QtGui.QVBoxLayout()
topHalfLayout.addLayout(cpLayout)
# define the capture controls (to go on controls panel)
capLayout = QtGui.QVBoxLayout()
def updatePlot(x, y):
x = np.asarray(x)
y = np.asarray(y)
self.plotWidget.clear()
self.plotWidget.plot(x, y, pen=mkPen("w", width=1))
self.plotWidget.addItem(self.cursorVert)
self.plotWidget.addItem(self.cursorHori)
vertLabel.setText(str(round(self.cursorVert.pos()[0], 2)))
horiLabel.setText(str(round(self.cursorHori.pos()[1], 2)))
def avgSpec():
oldAvgSpec = self.specProcessed
addThis = self.spec - self.darkSpectrum
self.numberAcquired += 1
if self.numberAcquired < self.numberToAverage:
scale = self.numberAcquired
else:
scale = self.numberToAverage
newAvg = ((scale - 1) * oldAvgSpec + addThis) / scale
self.specProcessed = newAvg
@inlineCallbacks
def capture():
self.spec = yield self.client.getSpectrum()
self.spec = np.asarray(self.spec)
self.time = yield self.client.getLastTime()
yield avgSpec()
updatePlot(self.wave, self.specProcessed)
self.timestamp.setText("last update: " + str(self.time))
@inlineCallbacks
def forcePress():
self.numberAcquired = 0
yield capture()
forceButton = QtGui.QPushButton("force")
forceButton.clicked.connect(forcePress)
capLayout.addWidget(forceButton)
autoRunLayout = QtGui.QHBoxLayout()
self.freeRunCall = LoopingCall(capture)
self.freeRunStatus = False
def freeRun():
if self.freeRunStatus:
freeButton.setText("start auto")
forceButton.setEnabled(True)
self.freeRunCall.stop()
self.freeRunStatus = False
self.numberAcquired = 0
return
if not self.freeRunStatus:
freeButton.setText("stop auto")
forceButton.setEnabled(False)
self.freeRunCall.start(autoRateSpin.value(), now=True)
#.........这里部分代码省略.........
示例4: QGraph
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addItem [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])
示例5: Aditi
# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import addItem [as 别名]
#.........这里部分代码省略.........
self.curr_scan_id_by_short_path[rawfile.short_path] = scan_ids[idx - 1]
elif evt.key() == Qt.Key_Right:
for rawfile in self.rawfiles_by_short_path.values()[:1]:
if not rawfile.is_checked:
continue
curr_scan_id = self.curr_scan_id_by_short_path[rawfile.short_path]
scan_ids = rawfile.reader.rt_by_scan_id_by_ms_level[1].keys()
idx = scan_ids.index(curr_scan_id)
times.append(rawfile.reader.rt_by_scan_id_by_ms_level[1][scan_ids[idx + 1]])
self.curr_scan_id_by_short_path[rawfile.short_path] = scan_ids[idx + 1]
self._plot_spectrum()
if times:
self.inf_line_tic_item.setPos(sum(times) / float(len(times)))
def _plot_spectrum(self):
self.plot_widget_spectrum.clear()
min_mz, max_mz = 1e9, 0
min_int, max_int = 1e10, 0
for rawfile in self.rawfiles_by_short_path.values():
if not rawfile.is_checked:
continue
scan_id, mzs, intensities = rawfile.reader.get_scan(self.curr_scan_id_by_short_path[rawfile.short_path])
min_mz = min(min_mz, mzs[0])
max_mz = max(max_mz, mzs[-1])
min_int = min(min_int, min(intensities))
max_int = max(max_int, max(intensities))
item = BarGraphItem(x=mzs, height=intensities, width=0.01, pen=rawfile.qcolor, brush=rawfile.qcolor)
self.plot_widget_spectrum.addItem(item)
self.plot_widget_spectrum.setLimits(xMin=min_mz, xMax=max_mz, yMin=min_int, yMax=max_int)
def plot_spectrum(self, ev):
#clear
if ev.button() == Qt.RightButton:
return
self.plot_widget_spectrum.clear()
vb = self.plot_widget_tic.vb
mouse_point = vb.mapSceneToView(ev.scenePos())
t = mouse_point.x()
if self.inf_line_tic_item is None:
self.inf_line_tic_item = InfiniteLine(pos=t, angle=90)
self.plot_widget_tic.addItem(self.inf_line_tic_item)
self.inf_line_tic_item.setMovable(True)
else:
self.inf_line_tic_item.setPos(t)
min_mz, max_mz = 1e9, 0
min_int, max_int = 1e10, 0
for rawfile in self.rawfiles_by_short_path.values():
if not rawfile.is_checked:
continue
scan_id, mzs, intensities = rawfile.reader.get_scan_for_time(t)
self.curr_scan_id_by_short_path[rawfile.short_path] = scan_id
min_mz = min(min_mz, mzs[0])
max_mz = max(max_mz, mzs[-1])
min_int = min(min_int, min(intensities))
max_int = max(max_int, max(intensities))