简体   繁体   English

seaborn x 轴两列的条形图

[英]Bar plot of two columns in x-axis in seaborn

My dataset is called df :我的数据集称为df

year french法语 flemish佛兰德语
2014 2014 200 200 200 200
2015 2015年 170 170 210 210
2016 2016年 130 130 220 220
2017 2017年 120 120 225 225
2018 2018 210 210 250 250

I want to create a histogram in seaborn with french and flemish on the x-axis and year as the hue.我想在flemish中创建一个直方图,在 x 轴上使用french和佛兰芒语,以year作为色调。

I tried this, but it didn't work successfully:我试过了,但没有成功:

sns.histplot(data=df, x="french", hue="year", multiple="dodge", shrink=.8)

The y-axis should show the height of the number of the columns of french and flemish . y 轴应显示frenchflemish列数的高度。

  1. You need to use a bar function, not a histogram function.您需要使用条形函数,而不是直方图函数。 Histogram functions take raw data and count them, but your data are already counted.直方图函数获取原始数据并对它们进行计数,但您的数据已经被计算在内。
  2. You need to melt the french and flemish columns into " long form ."您需要将frenchflemishmelt为“ 长式”。 Then x will be the language, and y will be the counts.然后x将是语言, y将是计数。
sns.barplot(data=df.melt("year", var_name="language", value_name="count"),
            x="language",
            y="count",
            hue="year")
plt.legend(loc=(1.05, 0))


The melted dataframe for reference:融化的数据框供参考:

>>> df.melt("year", var_name="language", value_name="count")

#    year  language  count
# 0  2014    french    200
# 1  2015    french    170
# 2  2016    french    130
# 3  2017    french    120
# 4  2018    french    210
# 5  2014   flemish    200
# 6  2015   flemish    210
# 7  2016   flemish    220
# 8  2017   flemish    225
# 9  2018   flemish    250

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM