【问题标题】:Add the label for the value to display above the bars [duplicate]添加值的标签以显示在条形上方[重复]
【发布时间】:2021-12-31 15:41:12
【问题描述】:

我创建了一个条形图,并希望将计数值放在每个条形上方。

# Import the libraries
import pandas as pd
from matplotlib import pyplot as plt

# Create the DataFrame
df = pd.DataFrame({
    'city_code':[1200013, 1200104, 1200138, 1200179, 1200203],
    'index':['good', 'bad', 'good', 'good', 'bad']
})

# Plot the graph
df['index'].value_counts().plot(kind='bar', color='darkcyan',
                                            figsize=[15,10])
plt.xticks(rotation=0, horizontalalignment="center", fontsize=14)
plt.ylabel("cities", fontsize=16)

我得到以下结果

我想在每个栏的顶部添加值。我从 value_counts 得到的 count 的值。 像这样的:

感谢所有提供帮助的人。

【问题讨论】:

标签: python pandas matplotlib graph


【解决方案1】:

可以使用ax.text一个一个添加标签,使用for循环。

但是 matplotlib 中已经有一个内置的method 可以做到这一点。

您可以将示例中的df['index'].value_counts().plot(kind='bar', color='darkcyan', figsize=[15,10]) 行更改为

d = df['index'].value_counts()
p = ax.bar(d.index, d.values,color='darkcyan')
ax.bar_label(p)

完整的例子是:

fig, ax = plt.subplots(figsize=(4, 3))
# Create the DataFrame
df = pd.DataFrame({
    'city_code':[1200013, 1200104, 1200138, 1200179, 1200203],
    'index':['good', 'bad', 'good', 'good', 'bad']
})

# Plot the graph
d = df['index'].value_counts()
p = ax.bar(d.index, d.values,color='darkcyan')
ax.bar_label(p)
plt.xticks(rotation=0, horizontalalignment="center", fontsize=14)
plt.ylabel("cities", fontsize=16)
fig.show()

输出图像如下所示:

【讨论】:

    【解决方案2】:

    使用patchesannotate 的示例:

    # Import the libraries
    import pandas as pd
    from matplotlib import pyplot as plt
    
    # Create the DataFrame
    df = pd.DataFrame(
        {
            "city_code": [1200013, 1200104, 1200138, 1200179, 1200203],
            "index": ["good", "bad", "good", "good", "bad"],
        }
    )
    
    # Plot the graph
    ax = df["index"].value_counts().plot(kind="bar", color="darkcyan", figsize=[15, 10])
    plt.xticks(rotation=0, horizontalalignment="center", fontsize=14)
    plt.ylabel("cities", fontsize=16)
    for p in ax.patches:
        ax.annotate(
            str(p.get_height()), xy=(p.get_x() + 0.25, p.get_height() + 0.1), fontsize=20
        )
    plt.savefig("test.png")
    
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-11
      • 2015-05-09
      • 1970-01-01
      • 2021-08-01
      • 2021-10-21
      相关资源
      最近更新 更多