熊猫图条形图及其值绘制

时间:2019-11-11 03:11:45

标签: python pandas matplotlib

如何在下面将此数据框及其值和百分比绘制在图表上?

    Activity Month  Total Monthly Actual Hours  Total Monthly Work Hours
0   Apr-19          35381.25                    42592
1   May-19          31722.50                    44528
2   Jun-19          27708.50                    38720
3   Jul-19          34283.50                    44528
4   Aug-19          32225.60                    42592

目前,我只能使用以下代码正常绘制它:

display(df.reset_index())

df.plot(kind='bar').tick_params(rotation = 0)
plt.ylabel('Work Hours')
plt.xlabel('Month')

enter image description here

我想将此图表绘制成这样:

enter image description here

1 个答案:

答案 0 :(得分:2)

一种即时计算百分比的方法:

df = pd.DataFrame(...)

ax = df.plot(kind='bar')

ax.tick_params(rotation = 0)

for date, (p, q) in enumerate(zip(df["Total_Monthly_Actual_Hours"],df["Total_Monthly_Work_Hours"])):
    ax.annotate(f"{p}\n({(p/q)*100:.0f}%)", (date-0.25, p*1.02), size=7)
    ax.annotate(f"{q}\n({(q/q)*100:.0f}%)", (date, q*1.02), size=7)

plt.ylabel('Work Hours')
plt.xlabel('Month')

plt.show()

enter image description here