pyqtgraph 堆叠条形图

pyqtgraph stacked bar graph

我有这组数据:

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 文档,但没有找到任何关于堆叠栏的信息。

我终于设法通过将先前条形图的高度传递给 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_()