【问题标题】:python - how to show values on top of bar plot [duplicate]python - 如何在条形图顶部显示值[重复]
【发布时间】:2019-04-03 15:10:36
【问题描述】:

这里是 Python 新手。我想在下图中显示每个 bin 上方的值:

这是我的代码:

x=[i for i in range(1,11)]
y=[0.95,
0.95,
0.89,
0.8,
0.74,
0.65,
0.59,
0.51,
0.5,
0.48]

plt.bar(x, height= y)
xlocs, xlabs = plt.xticks()
xlocs=[i+1 for i in range(0,10)]
xlabs=[i/2 for i in range(0,10)]
plt.xlabel('Max Sigma')
plt.ylabel('Test Accuracy')
plt.xticks(xlocs, xlabs)
plt.show()

这是我想要的图表:

【问题讨论】:

  • @Dan,如果这不是重复的,您需要通过展示您的研究来告诉我们为什么不这样做。
  • 我看到了其他评论,但我无法用我的代码做到这一点

标签: python matplotlib


【解决方案1】:

试试:

plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True This makes it simple

【讨论】:

  • 这只会将列标签放在顶部,而不是值
【解决方案2】:

plt.text() 将允许您向图表添加文本。它只允许您一次将文本添加到一组坐标,因此您需要遍历数据以为每个条添加文本。

以下是我对您的代码所做的主要调整:

# assign your bars to a variable so their attributes can be accessed
bars = plt.bar(x, height=y, width=.4)

# access the bar attributes to place the text in the appropriate location
for bar in bars:
    yval = bar.get_height()
    plt.text(bar.get_x(), yval + .005, yval)

我将.005 添加到 y 值,以便将文本放置在条形上方。这可以修改以获得您正在寻找的外观。

以下是基于原始代码的完整工作示例。我做了一些修改以使其不那么脆弱:

import matplotlib.pyplot as plt

# set the initial x-values to what you are wanting to plot
x=[i/2 for i in range(10)]
y=[0.95,
0.95,
0.89,
0.8,
0.74,
0.65,
0.59,
0.51,
0.5,
0.48]

bars = plt.bar(x, height=y, width=.4)

xlocs, xlabs = plt.xticks()

# reference x so you don't need to change the range each time x changes
xlocs=[i for i in x]
xlabs=[i for i in x]

plt.xlabel('Max Sigma')
plt.ylabel('Test Accuracy')
plt.xticks(xlocs, xlabs)

for bar in bars:
    yval = bar.get_height()
    plt.text(bar.get_x(), yval + .005, yval)

plt.show()

【讨论】:

    【解决方案3】:

    简单添加

    for i, v in enumerate(y):
        plt.text(xlocs[i] - 0.25, v + 0.01, str(v))
    

    plt.show() 之前。您可以通过分别更改 (-0.25) 和 (0.01) 值来调整文本的集中度或高度。

    【讨论】:

    • 可以添加参数horizontalalignment="center"而不是调整x偏移
    • 当增加 + 0.01 到 0.1 或 0.08 时高度没有变化
    • verticalalignment="bottom" 和 y 也是如此。
    猜你喜欢
    • 2013-02-20
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多