【问题标题】:pyqtgraph stacked bar graphpyqtgraph 堆积条形图
【发布时间】:2022-01-22 20:31:19
【问题描述】:

我有这组数据:

import pandas as pd

df = pd.DataFrame({'x': ['A', 'B', 'C', 'D'],
                   'y1': [10, 20, 10, 30],
                   'y2': [20, 25, 15, 25],
                   'y3': [5, 10, 5, 20]})
df = df.set_index('x')
   y1  y2  y3
x
A  10  20   5
B  20  25  10
C  10  15   5
D  30  25  20

我想在pyqtgraph中画一个类似于这个的堆积条形图,在matplolib中绘制:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
  
bottom = np.zeros(len(df))
for col in df.columns:
    ax.bar(df.index, df[col], bottom = bottom, label = col)
    bottom += df[col]

ax.legend(frameon = True)

plt.show()

我查看了pyqtgraph.BarGraphItem 文档,但没有找到任何关于堆叠条的信息。

【问题讨论】:

    标签: python data-visualization bar-chart pyqtgraph


    【解决方案1】:

    我终于设法通过将先前条的高度传递给pyqtgraph.BarGraphItemy0 参数来堆叠条:

    import pandas as pd
    import pyqtgraph as pg
    from pyqtgraph.Qt import QtGui
    import numpy as np
    from matplotlib import cm
    
    
    df = pd.DataFrame({'x': [1, 2, 3, 4],
                       'y1': [10, 20, 10, 30],
                       'y2': [20, 25, 15, 25],
                       'y3': [5, 10, 5, 20]})
    df = df.set_index('x')
    
    
    window = pg.plot()
    
    bottom = np.zeros(len(df))
    cmap = cm.get_cmap('tab10')
    colors = [tuple(255*x for x in cmap(i/10))[:-1] for i in range(len(df.columns))]
    
    for col, color in zip(df.columns, colors):
        bargraph = pg.BarGraphItem(x = df.index, height = df[col], y0 = bottom, width = 0.6, brush = pg.mkBrush(color = color), pen = pg.mkPen(color = color))
        window.addItem(bargraph)
        bottom += df[col]
    
    QtGui.QApplication.instance().exec_()
    

    【讨论】:

      猜你喜欢
      • 2017-02-26
      • 2014-02-09
      • 2016-01-19
      • 2020-09-14
      • 1970-01-01
      • 2016-10-13
      • 2017-10-14
      • 2019-01-14
      相关资源
      最近更新 更多