繁体   English   中英

按列或行拆分 sns.barplot

[英]Split sns.barplot by col or row

我想拆分我的 sns.barplot 以便第二行或第二列可以显示第二个条件。 具体来说,我希望使用 sns.barplot 而不是 facetgrid 的 catplot,这样我就可以显示条形的高度,并控制 tick_params。 有人有建议吗? 下面是使用titantic数据集的示例。

当前工作的代码没有按例如性别分割:

url = "https://raw.github.com/mattdelhey/kaggle-titanic/master/Data/train.csv"
titanic = pd.read_csv(url)

g = sns.barplot(data=titanic, 
            x='embarked',
            y='fare', 
            )

plt.ylim(0, 100)

#add height of bars
for p in g.patches:
    height = p.get_height()
    g.text(p.get_x()+p.get_width()/2,
            height+20,
            '{:}'.format(height.round(2)),
            ha="center") 

g.tick_params(axis='x', labelsize=20)

我想要的是这样的,我可以按性别将图表分成两列:

g = sns.barplot(data=titanic, 
            x='embarked',
            y='fare', 
            col='sex',
            )

plt.ylim(0, 100)

#add height of bars
for p in g.patches:
    height = p.get_height()
    g.text(p.get_x()+p.get_width()/2,
            height+20,
            '{:}'.format(height.round(2)),
            ha="center") 

g.tick_params(axis='x', labelsize=20)

同样,虽然我知道 catplot 能够做到这一点,但我失去了显示条形高度的能力。 hue也不是我想要的,因为我的实际数据集比titanic数据集更复杂,每个条件都应该显示在它自己的部分中。 谢谢!

正如@mwaskom sns.catplot的评论中提到的, FacetGrid object 有多个Axes ,您需要循环遍历。 您可以使用for ax in g.axes.flat:和 THEN for p in ax.patches:来完成此操作。 此外,您需要将kind='bar' to catplot and change to ax.text`:

url = "https://raw.github.com/mattdelhey/kaggle-titanic/master/Data/train.csv"
titanic = pd.read_csv(url)
#----------------------------------------
g = sns.catplot(data=titanic, 
            x='embarked',
            y='fare', 
        col='sex', kind='bar')

plt.ylim(0, 100)

# add height of bars
for ax in g.axes.flat:
    for p in ax.patches:
        height = p.get_height()
        ax.text(p.get_x()+p.get_width()/2,
                height+20,
                '{:}'.format(height.round(2)),
                ha="center") 

    ax.tick_params(axis='x', labelsize=20)

在此处输入图像描述

暂无
暂无

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

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