【问题标题】:Adding data labels ontop of my histogram Python/Matplotlib在我的直方图 Python/Matplotlib 上添加数据标签
【发布时间】:2022-01-21 17:35:03
【问题描述】:

我正在尝试在我的直方图顶部添加数据标签值以尝试显示频率。

这是我现在的代码,但不确定如何编写代码以将值放在顶部:

plt.figure(figsize=(15,10))
plt.hist(df['Age'], edgecolor='white', label='d')
plt.xlabel("Age")
plt.ylabel("Number of Patients")
plt.title = ('Age Distrubtion') 

我想知道是否有人知道执行此操作的代码:

【问题讨论】:

标签: python matplotlib annotations bar-chart histogram


【解决方案1】:

您可以通过plt.hist() 返回的条形使用新的bar_label() 函数。

这是一个例子:

from matplotlib import pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({'Age': np.random.randint(20, 60, 200)})

plt.figure(figsize=(15, 10))
values, bins, bars = plt.hist(df['Age'], edgecolor='white')
plt.xlabel("Age")
plt.ylabel("Number of Patients")
plt.title = ('Age Distrubtion')
plt.bar_label(bars, fontsize=20, color='navy')
plt.margins(x=0.01, y=0.1)
plt.show()

PS:由于年龄是离散分布,建议明确设置 bin 边界,例如plt.hist(df['Age'], bins=np.arange(19.999, 60, 5)).

【讨论】:

    【解决方案2】:

    plt.ylabel() 带有一个名为loc 的参数,可用于定义标签的位置:

    plt.ylabel("Age", loc="top")
    

    如果要手动控制,可以使用**kwargs 参数传入Text 对象(documentation),该对象可以接受xy 坐标值来放置文本。

    plt.ylabel("Age", text(x=100, y=200, rotation='horizontal'))
    

    【讨论】:

    • 嘿伙计,感谢您的回复,但是当我运行该代码时,我收到以下错误:ValueError:'top' is not a valid value for loc;支持的值为“左”、“中心”、“右”
    • @RubenVellupillai 我相信您正在运行 plt.xlabel() 而不是 plt.ylabel() 的代码
    • 抱歉再次询问,但我收到另一个错误 NameError: name 'text' is not defined
    • @RubenVellupillai 通过import matplotlib.pyplot.text as text导入模块
    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2020-11-21
    • 2018-05-18
    • 2013-04-03
    • 2015-05-09
    相关资源
    最近更新 更多