将数据值添加到带有数据框的条形图/折线图中有很多问题和解决方案。但是我有一种独特的情况,我想根据显示值的数据透视图创建图。
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))
但是我喜欢在如下所示的这些栏中显示值
答案 0 :(得分:1)
您可以为图中的每个色块添加文本:
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))
输出: