在直方图上添加数据标签 Python/Matplotlib

Rub*_*lai 7 python annotations matplotlib histogram bar-chart

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

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

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

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

在此输入图像描述

Joh*_*anC 18

bar_label()您可以使用返回的条形图来使用新函数plt.hist()

这是一个例子:

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

plt.hist() 和 plt.bar_label()

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

  • 请注意,“bar_label”仅在 matplotlib 版本 3.4 或更高版本中可用。 (3认同)