[英]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 軸的單個圖形中。
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.618
和17.392
之間正好有 68 張總鈔票。 右軸僅說明有關 kde 的信息。 例如,對於x=20
,y 值為0.043
意味着總賬單有大約 4.3 % 的可能性在19.5
和20.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)
請注意,如果直方圖使用 10 次方的 bin 寬度(例如sns.histplot(..., bins=np.arange(0, df['total_bill'].max()+10, 10)
). 最合適的 bin 很大程度上取決於您希望如何解釋數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.