【问题标题】:Display the percentage of colored portions on the level Matplotlib Python在级别 Matplotlib Python 上显示彩色部分的百分比
【发布时间】:2019-07-18 23:40:22
【问题描述】:

这是我从 matplotlib 的样本集中获取的示例:

import numpy as np
import matplotlib.pyplot as plt


N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence
fig = plt.Figure()
ax = fig.add_subplot(111)
p1 = ax.bar(ind, menMeans, width, yerr=menStd)
p2 = ax.bar(ind, womenMeans, width,
             bottom=menMeans, yerr=womenStd)

for p in ax.patches:
    width, height = p.get_width(), p.get_height()
    x, y = p.get_xy() 
    ax.annotate('{:.0%}'.format(height), (p.get_x()+.15*width, p.get_y() + height + 0.01))
    
    
plt.show()

参考资料在这里:Example in Docs
成功得到下图:

我想知道如何显示橙色条和蓝色条在其水平上方的百分比?

我已经尝试过以下解决方案:Display percentage above bar chart in matplotlib
我仍然什么也没看到。
让我提前澄清一下我想要什么,我想显示它的水平上方的蓝色部分和上方的橙色部分的百分比。我希望我很清楚。

【问题讨论】:

  • 你为什么使用plt.Figure?将那一行和...subplot(111) 替换为fig, ax = plt.subplots() 可以解决问题。
  • 我已经以类似的方式设置了我的其他结构。因此我尝试用这里的例子来复制它。
  • Jaffer,我收到了您的评论通知(虽然我不确定 StackOverflow 为何决定通知我,但您没有标记我)。我不能代表这两个投票者,但我只是想消除负面情绪。有时网站的动态并不是您所期望的,但您真的不应该把它当作个人或继续思考它。
  • 当我开始使用 Cython 时,我 asked a question 更有经验的用户可能觉得太琐碎了:它被否决了两次。但对我来说这个问题非常真实,我在问之前谷歌了很多,问了一个同事,答案真的让我进步了。
  • ????。请继续提问和回答。这两个反对票很快就会从您的记忆中消失!

标签: python matplotlib


【解决方案1】:

循环遍历 menMeanswomenMeans 中的值应该会得到你想要的:

import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

fig, ax = plt.subplots(1,1)
p1 = ax.bar(ind, menMeans, width, yerr=menStd)
p2 = ax.bar(ind, womenMeans, width,
             bottom=menMeans, yerr=womenStd)

for id, men in enumerate(menMeans):
    ax.text(id, men+3, str('{}\%'.format(men)))
    ax.text(id, men+womenMeans[id]+3, str('{}\%'.format(womenMeans[id])))

如果您希望将总百分比绘制在女性的条形之上,而不是女性的百分比,您可以这样做:

for id, men in enumerate(menMeans):
    ax.text(id, men+3, str('{}\%'.format(men)))
    ax.text(id, men+womenMeans[id]+3, str('{}\%'.format(womenMeans[id]+men)))

【讨论】:

  • 我可以写什么格式来获得小数点后 2 位的值?获取非常大的值。
  • 是的,你可以这样做:ax.text(id, men+3, str('{:0.2f}\%'.format(men)))
  • 感谢您告诉我
猜你喜欢
  • 2015-08-23
  • 2021-09-17
  • 2016-12-10
  • 2021-04-13
  • 2021-05-19
  • 1970-01-01
  • 2011-03-03
  • 2019-05-23
  • 1970-01-01
相关资源
最近更新 更多