[英]pyqtgraph stacked bar graph
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
:我想在 pyqtgraph 中绘制一个类似于这个的堆叠条形图,在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()
I have checked pyqtgraph.BarGraphItem
documentation but I didn't find any information regarding stacking bar.我检查了pyqtgraph.BarGraphItem
文档,但没有找到有关堆叠条的任何信息。
I finally managed to stack the bars by passing the height of the previous bars to pyqtgraph.BarGraphItem
's y0
parameter:我终于设法通过将先前条形的高度传递给pyqtgraph.BarGraphItem
的y0
参数来堆叠条形:
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_()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.