显示大熊猫密度图中的平均线

xxx*_*xxx 0 python plot matplotlib pandas

我使用.plot()方法创建一个图形

df['age'].plot(kind='density')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我没有使用"plt"对象创建图形:有没有办法用.plot()的参数显示虚线作为平均值.

我总是很不清楚如何处理属性和plt之间的差异:

x = df['age'].values
result = plt.hist(x, bins=15, color='c')
plt.axvline(x.mean(), color='b', linestyle='dashed', linewidth=2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

而且,我如何注释接近虚线的平均值?

Nic*_*eli 6

# Set seed to reproduce the results
np.random.seed(42)
# Generate random data
df = pd.DataFrame(dict(age=(np.random.uniform(-20, 50, 100))))

# KDE plot
ax = df['age'].plot(kind='density')
# Access the child artists and calculate the mean of the resulting array
mean_val = np.mean(ax.get_children()[0]._x)
# Annotate points
ax.annotate('mean', xy=(mean_val, 0.008), xytext=(mean_val+10, 0.010),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )
# vertical dotted line originating at mean value
plt.axvline(mean_val, linestyle='dashed', linewidth=2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

选择切片0,因为它对应于matplotlib.lines.Line2D轴对象的位置.

>>> np.mean(ax.get_children()[0]._x)
14.734316880344197
Run Code Online (Sandbox Code Playgroud)