python - 如何在条形图上添加值标签

标签 python pandas matplotlib seaborn bar-chart

我陷入了一些感觉应该相对容易的事情上。我在下面带来的代码是基于我正在处理的一个更大项目的示例。我认为没有理由发布所有详细信息,因此请按原样接受我带来的数据结构。

基本上,我正在创建一个条形图,我可以弄清楚如何在条形图上添加值标签(在条形图的中心,或正上方)。一直在网上查看示例,但没有成功实现我自己的代码。我相信解决方案是使用“文本”或“注释”,但我: a) 不知道使用哪个(一般来说,还没有弄清楚何时使用哪个)。 b) 看不到任何一个来呈现值(value)标签。 感谢您的帮助,我的代码如下。 提前致谢!

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.mpl_style', 'default') 
%matplotlib inline

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]

# In my original code I create a series and run on that, 
# so for consistency I create a series from the list.
freq_series = pd.Series(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0, 
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
fig = freq_series.plot(kind='bar')
fig.set_title('Amount Frequency')
fig.set_xlabel('Amount ($)')
fig.set_ylabel('Frequency')
fig.set_xticklabels(x_labels)

enter image description here

最佳答案

首先 freq_series.plot 返回一个轴 not 一个数字,所以为了让我的答案更清楚一点,我已经更改了您给定的代码以将其称为 ax 而不是 fig 以与其他代码示例更加一致。

您可以从 ax.patches 成员中获取绘图中生成的条形列表。然后你可以使用 this matplotlib gallery example 中演示的技术。使用 ax.text 添加标签方法。

import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series(frequencies)

x_labels = [
    108300.0,
    110540.0,
    112780.0,
    115020.0,
    117260.0,
    119500.0,
    121740.0,
    123980.0,
    126220.0,
    128460.0,
    130700.0,
]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind="bar")
ax.set_title("Amount Frequency")
ax.set_xlabel("Amount ($)")
ax.set_ylabel("Frequency")
ax.set_xticklabels(x_labels)

rects = ax.patches

# Make some labels.
labels = [f"label{i}" for i in range(len(rects))]

for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(
        rect.get_x() + rect.get_width() / 2, height + 5, label, ha="center", va="bottom"
    )

plt.show()

这会生成一个标记图,如下所示:

enter image description here

关于python - 如何在条形图上添加值标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28931224/

相关文章:

python - 在Python中,是否有对异常引发者的引用?

python - 值错误 : cannot reshape array of size 30470400 into shape (50, 1104,104)

python - 取组中的最大值,忽略当前行的值

python - 计算两个矩形之间的重叠面积

python - Matplotlib:采样数据时动态重新标记 x 轴

python - networkx.draw() 的 pos 参数不起作用

python - 如何创建内存中图像

python - 有没有办法让 python 脚本用旧文件替换新文件

python - pandas 在包含数字和字符串的列中应用小数

python - 如何查找类别中的唯一单词 - Python