在堆叠条形图中显示值 pandas
Show values in stacked bar chart pandas
我有这个 pandas 数据框:
production consumption
year
2013 0.426669 0.573331
2014 0.436364 0.563636
2015 0.419941 0.580059
2016 0.448378 0.551622
2017 0.442212 0.557788
2018 0.422724 0.577276
2019 0.445296 0.554704
然后我使用 df.plot.bar(stacked=True) 函数
绘制堆积条形图
产量和消耗量在 %
是否可以将百分比添加到条中?
这比它应该的更难,但它是可行的:
ax = df.plot.bar(stacked=True)
labels = [f'{i:.0%}' for i in df.to_numpy().flatten(order='F')]
for i, patch in enumerate(ax.patches):
x, y = patch.get_xy()
x += patch.get_width() / 2
y += patch.get_height() / 2
ax.annotate(labels[i], (x, y), ha='center', va='center', c='white')
结果:
我有这个 pandas 数据框:
production consumption
year
2013 0.426669 0.573331
2014 0.436364 0.563636
2015 0.419941 0.580059
2016 0.448378 0.551622
2017 0.442212 0.557788
2018 0.422724 0.577276
2019 0.445296 0.554704
然后我使用 df.plot.bar(stacked=True) 函数
绘制堆积条形图产量和消耗量在 %
是否可以将百分比添加到条中?
这比它应该的更难,但它是可行的:
ax = df.plot.bar(stacked=True)
labels = [f'{i:.0%}' for i in df.to_numpy().flatten(order='F')]
for i, patch in enumerate(ax.patches):
x, y = patch.get_xy()
x += patch.get_width() / 2
y += patch.get_height() / 2
ax.annotate(labels[i], (x, y), ha='center', va='center', c='white')
结果: