我正在尝试创建一个堆叠条形图,它在 x 轴上有两个类别,在这种情况下,我希望按组然后按年份。
我目前在 PyCharm 中使用 Python 3。我已经在 excel 中创建了一个模型来实现我的目标。
如果我在 Excel 中使用我的示例代码并创建一个数据透视图,我可以创建我正在寻找的确切图形。我已将 Excel 中的图表和示例数据放在 Google 表格中,以便您查看:
https://docs.google.com/spreadsheets/d/1jov0DwcMA8wUFXLSo88b-MfzfRI-BaOQF8PVjzogA0o/edit?usp=sharing
假设您将数据保存到一个csv
名为tmp.csv
(导出到csv
Excel 中)的文件中,那么此脚本可以构建您想要的图形
import pandas as pd
from matplotlib import pyplot as plt
tmp = pd.read_csv('tmp.csv')
tmp_small = tmp.drop(['Group', 'Year'], axis=1)
year = tmp.loc[:, 'Year'].values
group = tmp.loc[:, 'Group'].values[[0, 2, 4]]
fig, ax = plt.subplots(figsize=(8, 6))
palette = ['r', 'g', 'b']
for ind in range(6):
tmp_values = tmp_small.iloc[ind].values
for count, item in enumerate(tmp_values):
offset = np.sum(tmp_values[:count]) if count > 0 else 0
ax.bar(x=ind, width=0.5, height=item, bottom=offset, color=palette[count])
ax.set_xticks(np.arange(len(year)))
ax.set_xticklabels(year)
ax.set_xlim(-1, 6.5)
ax.text(0.3, -10, group[0])
ax.text(2.3, -10, group[1])
ax.text(4.3, -10, group[2])
输出图是
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句