簡體   English   中英

帶有兩個 y 軸的 Seaborn displot

[英]Seaborn displot with two y axes

如何使用 Seaborn 的 displot 和兩個 y 軸創建直方圖:一個顯示計數,另一個顯示相應的密度? 我試過這段代碼,但結果沒有意義:

ax = sns.distplot( df_flavors.Freq, kde = False )
ax.set_title( 'Distribution of Flavor Purchases\nNumber Purchased', fontsize = font_title )
ax.set( ylabel = 'Count', xlabel = 'Number of Flavors Purchased' )
ax.set_xticks( range( n ))
ax.set_xticklabels( range( n ) )
##
ax2 = plt.twinx()

DataFrame df_flavors 是一個包含 2000 條記錄的大型 DataFrame,每條記錄都顯示人們購買了多少種不同口味的酸奶(0 - 7 種口味)。 這些人是 n = 2000 的調查的受訪者。變量 Freq 是每個受訪者的計數。 sns.distplot 在左軸上生成計數; 沒關系。 ax2 = plt.twinx() 產生第二個 y 軸,但不是該軸上的百分比,只是累積百分比; 那不行。 有什么建議可以在右邊獲得總 2000 的百分比或密度嗎?

在一個軸上,可以繪制沒有 kde 的直方圖。 另一方面是沒有直方圖的kde。 左側 y 軸將包含計數,右側將包含密度。

import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt

# generate some random test data
y = np.abs(np.random.normal(np.random.choice([5, 9, 15], 2000, p=[3/9, 5/9, 1/9]), 2, 2000))

ax = sns.distplot(y, kde=False)
ax.set_title('Distribution of Flavor Purchases\nNumber Purchased')
ax.set(ylabel='Count', xlabel='Number of Flavors Purchased')
n = 20
ax.set_xticks(range(n))
ax.set_xticklabels(range(n))

ax2 = plt.twinx()
ax2 = sns.distplot(y, kde=True, hist=False, ax=ax2)
ax2.set_ylabel('density')
plt.show()

示例圖

暫無
暫無

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

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