Reputation: 12496
I have this set of data:
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
I want to draw a stacked bar chart in pyqtgraph
similar to this one, drawn in 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()
I have checked pyqtgraph.BarGraphItem
documentation but I didn't find any information regarding stacking bar.
Upvotes: 0
Views: 1230
Reputation: 12496
I finally managed to stack the bars by passing the height of the previous bars to pyqtgraph.BarGraphItem
's y0
parameter:
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_()
Upvotes: 1