如何显示百分比和条形图

Firdhaus Saleh

我已经为下面的数据绘制了条形图

                Total Monthly Actual Hours  Total Monthly Work Hours
Activity Month
Apr-19          35381.25                    42592
May-19          31722.50                    44528
Jun-19          27708.50                    38720
Jul-19          34283.50                    44528
Aug-19          21359.90                    42592

到目前为止我的代码

display(dfWorkActual)

dfWorkActual.plot(kind='bar')
plt.ylabel('Work Hours')
plt.xlabel('Month')
plt.title("Total Monthly Work Hours & Total Actual Work Hours vs Month")

图表

现在,我想添加每月总时数中实际总时数的百分比。

例如:

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

请指教

阿比希尔

要注释条形图,您可以在此处参考matplotlib文档中的示例。

https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py

fig = plt.figure(figsize=(15,10))
ax = plt.gca()
width = 0.35
rects1 = ax.bar(df.index-width/2, df.A, width)
rects2 = ax.bar(df.index+width/2, df.B, width)
for r1, r2 in zip(rects1, rects2):
    h1 = r1.get_height()
    h2 = r2.get_height()
    percent = int(h1 * 100 / h2)
    ax.annotate('{}%'.format(percent),
                    xy=(r1.get_x() + r1.get_width() / 2, h1),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
    ax.annotate('100%',
                    xy=(r2.get_x() + r2.get_width() / 2, h2),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

plt.show()

在此处输入图片说明

fig = plt.figure(figsize=(15,10))
ax = plt.gca()
width = 0.35
rects1 = ax.bar(df.index, df.A, width)
rects2 = ax.bar(df.index, df.B, width, bottom=df.A)
for r1, r2 in zip(rects1, rects2):
    h1 = r1.get_height()
    h2 = r2.get_height()
    percent = int(h1 * 100 / h2)
    ax.annotate('{}%'.format(percent),
                    xy=(r1.get_x() + r1.get_width() / 2, h1/2),
                    xytext=(0, 0),
                    textcoords="offset points",
                    ha='center', va='bottom')
    ax.annotate('100%',
                    xy=(r2.get_x() + r2.get_width() / 2, h1+h2/2),
                    xytext=(0, 0), 
                    textcoords="offset points",
                    ha='center', va='bottom')

plt.show()

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章