我想绘制堆叠条形图。前3个条形图为红色、黑色和蓝色,如下所示。
我想添加一个第四条,它是红色,黑色和蓝色条值的“总和”。
(In在另一种情况下,我想添加第四个条形,即红、黑、蓝条形的“平均值”。)
例如,这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
n_bins = 20
x = np.random.randn(1000, 3)
fig, ax0 = plt.subplots(nrows=1, ncols=1)
colors = ['red', 'black', 'blue']
ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')
fig.tight_layout()
plt.show()
这个数字不包括第四条。
任何建议如何我可以显示在这个堆栈条形图第4条?
1条答案
按热度按时间klsxnrf11#
使用
np.histogram
计算每组的hist
和bin_edges
,计算每组的总和和平均值,并使用每个箱的绝对条形高度绘制条形图。绘制分组或堆叠条形图的最简单方法是从
pandas.DataFrame
和pandas.DataFrame.plot
。在
python 3.11.2
、pandas 2.0.1
、matplotlib 3.7.1
、numpy 1.24.3
中测试.iloc
或y=['s0', 's1', 's2', 'mean']
选择要打印的特定列。