使用 pyqt 创建条形图

Creating a Barplot using pyqt

我需要用 pyqtgraph 绘制动画条形图。对于动画,我指的是图表,它更新串行端口给出的值。现在,一个非动画情节就足够了。我想实现一个看起来像这样的情节:

我的输入数据在字典中给出,如下所示:(Key=Timestamp, Value=Event)

{1604496095: 0, 1604496096: 4, 1604496097: 6, 1604496098: 8, 1604496099: 9, 1604496100: 7, 1604496101: 8 ... }

很遗憾,我无法提供很多代码,因为我无法创建与图片中的图表类似的图表。目前我只有对应的window

那是我现在的 window:

from PyQt5 import QtGui, QtWidgets, QtCore
import pyqtgraph as pg
import sys

class Plotter(QtWidgets.QMainWindow):
    def __init__(self, *args):
        QtWidgets.QMainWindow.__init__(self, *args)
        self.setWindowTitle("Test-Monitor")
        self.setMinimumSize(QtCore.QSize(800, 400))
        self.setupUI()

    def setupUI(self):
        self.plot = pg.PlotWidget()
        self.plot.showGrid(x=True, y=True)
        self.plot.setLabel('left', 'Event')
        self.plot.setLabel('bottom', 'Time')

        self.setCentralWidget(self.plot)


app = QtWidgets.QApplication(sys.argv)
plotter = Plotter()
plotter.show()
app.exec_()

我将不胜感激使用与图片接近的 pyqtgraph 的代码示例。

您可以使用 BarGraphItem,并使用值数组添加所有“条形图”(或者添加单独的 BarGraphItems,如果您愿意):

    def buildData(self, data):
        stamps = sorted(data.keys())
        zero = min(stamps)
        x0 = []
        y0 = []
        width = []
        brushes = []
        for i, stamp in enumerate(stamps):
            try:
                nextStamp = stamps[i + 1]
            except:
                nextStamp = stamp + 1
            x0.append(stamp - zero)
            y0.append(data[stamp])
            width.append(nextStamp - stamp)
            brushes.append(QtGui.QColor(QtCore.Qt.GlobalColor(data[stamp])))

        barItem = pg.BarGraphItem(x0=x0, y0=y0, width=width, height=1, 
            brushes=brushes)
        self.plot.addItem(barItem)

请注意,仅出于此示例的目的,使用 Qt.GlobalColor 选择画笔颜色,您可能应该使用 returns 基于值的颜色的字典或函数。