首页 > 解决方案 > 在堆积条形图中注释一个变量

问题描述

我有一个条形图,它从一组中获取最大值,然后将剩余的较低值聚合在一起并将它们集中到一个“其他”组中。

如何在忽略其他组的同时仅注释最大值组。

我在这里找到的用于条形图注释的代码通常效果很好,但会注释两个图表。有人知道我该如何解决吗?

例如,这是我的问题的一个示例

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

d = {'Group': ['a'], '6 Month Projection': [100]}
dff = pd.DataFrame(data=d)
# dff['6 Month Projection'] = dff['6 Month Projection']/1000000
# dff
fig, ax = plt.subplots()

x_bar = dff['Group']
y_bar = dff['6 Month Projection'][0]
z_bar = 50
# plt.bar(x_bar,y_bar)



plt.bar(x_bar, z_bar)
plt.bar(x_bar, y_bar, bottom=z_bar,color='orange')


for p in ax.patches:
    ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')



fig.text(0.9, 0.05, '$Group$')
fig.text(0.1, 0.95, 'Revenue in Millions')
# ax.set_ylim(bottom=10.00)
# ax.set_ylim(top=12.75)
# fig.set_size_inches(10,5)
plt.show()
# # plt.xticks(y_pos, objects)
# # plt.ylabel('Usage')
# # plt.title('Programming language usage')

# plt.show()

有谁知道我如何只注释蓝色?

标签: pythonpandasmatplotlib

解决方案


有很多方法可以实现您想要的。最简单的方法是在仅创建底部的补丁时循环创建补丁。另一种方法是测试条的 y 位置是否为零:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

d = {'Group': ['a'], '6 Month Projection': [100]}
dff = pd.DataFrame(data=d)
fig, ax = plt.subplots()

x_bar = dff['Group']
y_bar = dff['6 Month Projection'][0]
z_bar = 50

ax.bar(x_bar, z_bar)
ax.bar(x_bar, y_bar, bottom=z_bar, color='orange')

for p in ax.patches:
    if p.get_y() == 0:
        ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center',
                    xytext=(0, 10), textcoords='offset points')

fig.text(0.9, 0.05, '$Group$')
fig.text(0.1, 0.95, 'Revenue in Millions')
plt.show()

注释下栏

一些评论:

  • fig, ax = subplots(...)您一起选择“面向对象”的绘图界面;建议继续使用ax来告诉 matplotlib 使用哪个“子图”。
  • 要将文本定位在栏的顶部,您需要p.get_y()与. 相加p.get_height()。(这对于底部为 0 的条形图没有影响。)

推荐阅读