【问题标题】:Creating a Barplot using pyqt使用 pyqt 创建条形图
【发布时间】:2021-02-19 12:48:01
【问题描述】:

我需要用 pyqtgraph 绘制一个动画条形图。对于动画,我的意思是一个图表,它会更新他由串行端口给出的值。目前,没有动画的情节就足够了。我想实现一个看起来像这样的情节:

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

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

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

这就是我现在的窗口:

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 的代码示例。

【问题讨论】:

    标签: python pyqt bar-chart pyqtgraph


    【解决方案1】:

    您可以使用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 选择画笔颜色只是为了本示例的目的,您可能应该使用字典或根据值返回颜色的函数。

    【讨论】:

    • 完美运行,谢谢。我还有一个问题,也许你可以帮助我。我想在图旁边制作一个复选框列表,我想将其连接到图中的条形图。我是否必须为每个单个值创建一个 pg.BarGraphItem 以显示或隐藏它们,或者这可以通过给定的解决方案实现吗?
    • 我不确定我是否理解。您希望能够单独显示/隐藏条形吗?如果是这种情况,是的,您必须创建单个项目,这是由于这些项目的绘制方式(它们实际上是 QPicture 实例)。
    • 是的,这正是我想做的。你有什么好的方法可以让我为每个单独的任务(Y)创建一个栏吗?
    • 我相信您可以使用以下参数创建单独的柱:BarGraphItem(x0=[x], y0=y, width=width, height=1, brushes=[brush]);请注意,在这种情况下,变量是每个条形图(而不是列表)的单独值,但 x0 和画笔参数必须是该类的数组,这就是它们括在方括号中的原因。
    • @enyo 请注意,如果您不需要特定的交互,您甚至可以使用简单的 QGraphicsRectItem。
    猜你喜欢
    • 2020-12-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2021-03-09
    相关资源
    最近更新 更多