簡體   English   中英

如何在 Seaborn 中為同一圖形上的直方圖生成兩個單獨的 Y 軸

[英]How to Generate Two Separate Y-Axes For A Histogram on the Same Figure In Seaborn

我想生成一個具有兩個 y 軸的圖形: Count (來自直方圖)和Density (來自 KDE)。

我想在 Seaborn >= v 0.11中使用sns.displot

import seaborn as sns

df = sns.load_dataset('tips')

# graph 1: This should be the Y-Axis on the left side of the figure
sns.displot(df['total_bill'], kind='hist', bins=10)

# graph 2: This should be the Y-axis on the right side of the figure
sns.displot(df['total_bill'], kind='kde')

我編寫的代碼生成了兩個單獨的圖表; 我可以只為兩個單獨的圖形使用一個平面網格,但我想要更簡潔,並將兩個單獨的網格上的兩個 y 軸放在一個共享相同 x 軸的單個圖形中。

seaborn_tips_dataset_dist

displot()是一個圖形級別的 function ,它可以在一個圖形內創建多個子圖。 因此,您無法控制各個軸。

要創建組合圖,您可以使用底層坐標區函數: histplot()kdeplot()用於 Seaborn v.0.11。 這些函數接受ax=參數。 twinx()創建第二個 y 軸。

import matplotlib.pyplot as plt
import seaborn as sns

df = sns.load_dataset('tips')

fig, ax = plt.subplots()

sns.histplot(df['total_bill'], bins=10, ax=ax)

ax2 = ax.twinx()
sns.kdeplot(df['total_bill'], ax=ax2)

plt.tight_layout()
plt.show()

結果圖

編輯:

如評論中所述,y 軸未對齊。 左軸僅說明有關直方圖的信息。 例如,高度為 68 的最高箱子意味着在12.61817.392之間正好有 68 張總鈔票。 右軸僅說明有關 kde 的信息。 例如,對於x=20 ,y 值為0.043意味着總賬單有大約 4.3 % 的可能性在19.520.5之間。

要對齊兩者類似於sns.histplot(..., kde=True) ,可以計算直方圖的面積(bin 寬度乘以數據值的數量)並用作比例因子。 當以像素為單位測量時,這種縮放將使直方圖的面積和 kde 曲線下方的面積相等:

num_bins = 10
bin_width = (df['total_bill'].max() - df['total_bill'].min()) / num_bins
hist_area = len(df) * bin_width
ax2.set_ylim(ymax=ax.get_ylim()[1] / hist_area)

縮放的kde圖

請注意,如果直方圖使用 10 次方的 bin 寬度(例如sns.histplot(..., bins=np.arange(0, df['total_bill'].max()+10, 10) ). 最合適的 bin 很大程度上取決於您希望如何解釋數據。

暫無
暫無

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

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