[英]python seaborn shows bar plots as same height for different class
I want to plot factor plots for my data. 我想为我的数据绘制因子图。 I tried doing it the below way but the chart values didn't turn out as expected.
我尝试按照以下方式进行操作,但图表值未达到预期。
df = pd.DataFrame({'subset_product':['A','A','A','B','B','C','C'],
'subset_close':[1,1,0,1,1,1,0]})
prod_counts = df.groupby('subset_product').size().rename('prod_counts')
df['prod_count'] = df['subset_product'].map(prod_counts)
g = sns.factorplot(y='prod_count',x='subset_product',hue='subset_close',data=df,kind='bar',palette='muted',legend=False,ci=None)
plt.legend(loc='best')
However, my plots all have the same height, meaning it didn't separate the data into '1' and '0'. 但是,我的绘图都具有相同的高度,这意味着它没有将数据分为“ 1”和“ 0”。
Example: For A
, the blue bar should have height = 1, and the green bar should have height = 2. 示例:对于
A
,蓝色条的高度应为1,绿色条的高度应为2。
The problem is your 'prod_count'
. 问题是您的
'prod_count'
。
print(df)
# subset_close subset_product prod_count
# 0 1 A 3
# 1 1 A 3
# 2 0 A 3
# 3 1 B 2
# 4 1 B 2
# 5 1 C 2
# 6 0 C 2
You are telling seaborn that y is 3 when subset_close == 1 & subset_product == A
and y is also 3 when subset_close == 0 & subset_product == A
. 您正在告诉seaborn,当
subset_close == 1 & subset_product == A
,y为3,当subset_close == 0 & subset_product == A
时,y也为3。
Below should do what you want. 下面应该做你想要的。
# Count the number of each (`subset_close`, `subset_product`) combination.
df2 = df.groupby(['subset_product', 'subset_close']).size().reset_index(name='prod_count')
# Plot
g = sns.factorplot(y='prod_count', x='subset_product', hue='subset_close', data=df2,
kind='bar', palette='muted', legend=False, ci=None)
plt.legend(loc='best')
plt.show()
print(df2)
# subset_product subset_close prod_count
# 0 A 0 1
# 1 A 1 2
# 2 B 1 2
# 3 C 0 1
# 4 C 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.