簡體   English   中英

在熊貓密度圖中顯示平均值線

[英]Showing the mean line in a density plot in pandas

我使用.plot()方法創建圖

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

在此處輸入圖片說明

我不使用“ 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)

在此處輸入圖片說明

此外,如何注釋接近虛線的均值?

# 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)

在此處輸入圖片說明

選擇了切片0,因為它對應於matplotlib.lines.Line2D軸對象的位置。

>>> np.mean(ax.get_children()[0]._x)
14.734316880344197

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM