在大Pandas密度图上显示平均线

2024-05-18 20:54:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

df['age'].plot(kind='density')

enter image description here

我不使用“plt”对象创建图形:有没有任何方法可以使用.plot()参数将虚线显示为平均值。在

我一直不清楚如何处理属性和plt之间的区别,例如:

^{pr2}$

enter image description here

再者,我如何在虚线附近注释平均值?在


Tags: 对象方法图形dfage参数属性plot
1条回答
网友
1楼 · 发布于 2024-05-18 20:54:18
# 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)

enter image description here

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

^{pr2}$

相关问题 更多 >

    热门问题