python - 在堆积条形图中注释一个变量
问题描述
我有一个条形图,它从一组中获取最大值,然后将剩余的较低值聚合在一起并将它们集中到一个“其他”组中。
如何在忽略其他组的同时仅注释最大值组。
我在这里找到的用于条形图注释的代码通常效果很好,但会注释两个图表。有人知道我该如何解决吗?
例如,这是我的问题的一个示例
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()
有谁知道我如何只注释蓝色?
解决方案
有很多方法可以实现您想要的。最简单的方法是在仅创建底部的补丁时循环创建补丁。另一种方法是测试条的 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 的条形图没有影响。)
推荐阅读
- scala - 使用 spark-submit 跟踪和记录/调试从 scala 二进制文件启动的纱线应用程序
- automated-tests - 空手道框架的 JSON 报告
- javascript - 我的多项目轮播在调整屏幕大小时折叠(引导)
- build - vsts中msbuild的路径是什么
- angular - Angular 5 字符串常量外化
- arrays - 如何将可观察对象和属性(字段)数组映射到属性?
- tcp - 发送一个大包与两个小包
- python - 如何在运行时访问容器内的环境变量?
- android - 从 Play 商店安装时,Android Cordova 应用程序崩溃
- c++ - 如何在 C++ 中将 '\' 替换为 '\\' 以处理转义序列?