简体   繁体   English

带有两个 y 轴的 Seaborn displot

[英]Seaborn displot with two y axes

How do I create a histogram using Seaborn's displot with two y axes: one showing count and the other showing the corresponding density?如何使用 Seaborn 的 displot 和两个 y 轴创建直方图:一个显示计数,另一个显示相应的密度? I tried this code but the result does not make sense:我试过这段代码,但结果没有意义:

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

The DataFrame df_flavors is a large DataFrame with 2000 records, each showing how many different flavors of yogurts people bought (0 - 7 flavors). DataFrame df_flavors 是一个包含 2000 条记录的大型 DataFrame,每条记录都显示人们购买了多少种不同口味的酸奶(0 - 7 种口味)。 The people are respondents to a survey with n = 2000. The variable Freq is the count for each respondent.这些人是 n = 2000 的调查的受访者。变量 Freq 是每个受访者的计数。 The sns.distplot produces the count on the left axis; sns.distplot 在左轴上生成计数; that's ok.没关系。 The ax2 = plt.twinx() produces a second y-axis but not percents on that axis, just cumulative percents; ax2 = plt.twinx() 产生第二个 y 轴,但不是该轴上的百分比,只是累积百分比; that's not ok.那不行。 Any suggestions for getting just percent or density of the total 2000 on the right?有什么建议可以在右边获得总 2000 的百分比或密度吗?

On one axis, the histogram without the kde could be drawn.在一个轴上,可以绘制没有 kde 的直方图。 And on the other the kde without the histogram.另一方面是没有直方图的kde。 The left y-axis will contain the count and the right the density.左侧 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