【问题标题】:Feeding PyQtGraph bar chart with 2D-Array使用 2D-Array 提供 PyQtGraph 条形图
【发布时间】:2021-11-06 02:51:20
【问题描述】:

我有这个二维数组:

[[200, 200, 215], [161, 162, 172], [72, 45, 31], [116, 75, 33], [182, 182, 195], [103, 63, 26], [151, 152, 156], [211, 211, 228], [190, 191, 204], [98, 75, 49], [93, 51, 23], [135, 135, 135], [117, 107, 84], [163, 99, 35], [172, 173, 184], [172, 173, 184]]

我想绘制直方图之类的东西。 这些是 RGB 值。

我想要做的是在 X 轴上绘制每个子数组(在本例中为 1)的数量,并在 Y 轴上打印为标签的对。是否可以像这样输入我的 PyQtGraph 并用相应的颜色为条形着色?

这是一个使用 Ruby 和 ChartJS 的示例:

【问题讨论】:

    标签: python pyqt pyqt5 bar-chart pyqtgraph


    【解决方案1】:

    您可以先删除底部轴刻度标签,然后将每个条添加为具有适当宽度的 pg.InfiniteLine 对象。

    使用AxisItem.setTicks(ticks)方法可以实现将y轴刻度标签改为r,g,b值。

    import sys
    from PyQt5.QtCore import Qt
    from PyQt5.QtWidgets import QApplication, QMainWindow
    import pyqtgraph as pg
    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k')
    
    class ColorBarPlot(pg.GraphicsLayoutWidget):
    
        def __init__(self):
            super(ColorBarPlot, self).__init__()
            self.p1 = pg.PlotItem() 
            self.addItem(self.p1)
            self.p1.getAxis('bottom').setStyle(showValues=False)
    
        def displayColors(self, colors):
            
            self.p1.clear()
            ticks = []
            for i, color in enumerate(colors):
                line = pg.InfiniteLine(
                    pos=i+1, # y value of the line 
                    angle=0, # horizontal, 90 is vertical 
                    pen=pg.mkPen(pg.mkColor(color[0], color[1], color[2]), width=15) # Set color
                )
                self.p1.addItem(line)
                ticks.append((i+1, '{},{},{}'.format(color[0], color[1], color[2])))
            self.p1.getAxis('left').setTicks([ticks])
    
    
    
    if __name__ == "__main__":
    
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        app = QApplication([])
        win = QMainWindow()
        plot = ColorBarPlot()
        win.setCentralWidget(plot)
        plot.displayColors([[200, 200, 215], [161, 162, 172], [72, 45, 31], [116, 75, 33], [182, 182, 195], [103, 63, 26], [151, 152, 156], [211, 211, 228], [190, 191, 204], [98, 75, 49], [93, 51, 23], [135, 135, 135], [117, 107, 84], [163, 99, 35], [172, 173, 184], [172, 173, 184]])
        win.show()
    
        if (sys.flags.interactive != 1) or not hasattr(Qt.QtCore, "PYQT_VERSION"):
            QApplication.instance().exec_()
    
    

    Result

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2023-03-29
    • 2022-01-22
    • 2020-08-04
    • 1970-01-01
    • 2017-12-16
    • 2020-08-04
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多