python-如何在条形图上显示值

Dan*_*an 4 python matplotlib

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()
Run Code Online (Sandbox Code Playgroud)

这是我想要的图形: 在此处输入图像描述

Mar*_*ran 8

只需添加

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

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

新剧情

  • 您可以添加参数 `horizo​​ntalalignment="center"` 而不是调整 x 偏移 (2认同)

小智 5

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)
Run Code Online (Sandbox Code Playgroud)

我添加.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()
Run Code Online (Sandbox Code Playgroud)