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

时间:2018-10-30 14:32:10

标签: python matplotlib

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

enter image description here

这是我的代码:

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()

这是我想要的图形: enter image description here

3 个答案:

答案 0 :(得分:3)

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)

我在y值上添加了.005,以便将文本放置在条形上方。可以对其进行修改以获得所需的外观。

下面是一个基于原始代码的完整示例。我进行了一些修改以使它也变脆:

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()

答案 1 :(得分:3)

只需添加

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

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

New plot

答案 2 :(得分:-1)

尝试:

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