python - 如何与条形图一起显示百分比

标签 python pandas matplotlib percentage

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

                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")

Chart

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

例如:

enter image description here enter image description here enter image description here

请指教

最佳答案

要注释条形图,您可以引用此处 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()

enter image description here

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()

enter image description here

关于python - 如何与条形图一起显示百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58689570/

相关文章:

python - 绘制与曲面相交的 3d 线

python - 为什么我们使用 `wraps` 而不是 `update_wrapper` 作为装饰器?

python - 如何在 Django 模板中获取 base_url

python - 是否可以读取一个空的 csv 文件?

python - 如果其他单元格包含 'something',如何在 2 个单元格中设置值

python - 来自 xyz 数据 : griddata invalid index 的 Matplotlib 轮廓

python - 比较2种颜色直方图,其中一种是从txt文件加载的

Python - 字符串和 now() 的时间增量

python - 如何按照某些标准将数据集拆分为子集?

python - 通过颜色定义从绘图中排除点?