使用数据框将数据值添加到条形图/线形图中存在许多问题和解决方案。但我有一个独特的情况,我想要从显示值的透视数据创建绘图。
from matplotlib.ticker import PercentFormatter
time_report = pd.DataFrame([["A", 6, "2020-1"], ["B", 8, "2020-1"],["A", 4,"2020-2" ], ["B", 5,"2020-2" ],["A", 3, "2020-2"],["B", 6,"2020-3" ],["A", 5, "2020-3"]], columns=['Team','Hours', 'Month'])
df_pivot_perc = pd.pivot_table(time_report, index='Team', columns='Month', values='Hours', aggfunc=sum).apply(lambda x:1 * x / float(x.sum())).round(2)
plt = df_pivot_perc.transpose().plot(kind='bar', stacked=True)
plt.yaxis.set_major_formatter(mtick.PercentFormatter(1))

但我喜欢下面这些条上的值

发布于 2020-06-23 22:53:48
可以为绘图中的每个补丁添加文本:
from matplotlib.ticker import PercentFormatter
time_report = pd.DataFrame([["A", 6, "2020-1"], ["B", 8, "2020-1"],["A", 4,"2020-2" ], ["B", 5,"2020-2" ],["A", 3, "2020-2"],["B", 6,"2020-3" ],["A", 5, "2020-3"]], columns=['Team','Hours', 'Month'])
df_pivot_perc = pd.pivot_table(time_report, index='Team', columns='Month', values='Hours', aggfunc=sum).apply(lambda x:1 * x / float(x.sum())).round(2)
plt = df_pivot_perc.transpose().plot(kind='bar', stacked=True)
# extract information from the patches and annotate:
for patch in plt.patches:
x,y = patch.get_xy()
width,height = patch.get_width(), patch.get_height()
plt.text(x+width/2, y + height/2, f'{height:.%}', va='center', ha='center')
plt.yaxis.set_major_formatter(PercentFormatter(1))输出:

https://stackoverflow.com/questions/62537593
复制相似问题