如何让seaborn catplot的hue dodge仅单分面生效不跨网格
解决方法
要实现hue偏移仅在单个分面内计算,你可以放弃直接在catplot中传入hue参数,改用FacetGrid手动逐分面绘制图形,每个分面单独调用柱状图接口,就会基于当前分面的数据子集计算hue偏移,不会预留其他分面的类别空位。
可运行实现代码
import seaborn as sns import matplotlib.pyplot as plt df = sns.load_dataset("penguins") df['category'] = 'small' df.category.mask(df.species == 'Gentoo', 'big', inplace=True) # 初始化分面网格 g = sns.FacetGrid(data=df, col='category', height=5) # 每个分面单独绘制带hue的柱状图 g.map_dataframe( sns.barplot, x='island', y='body_mass_g', hue='species', dodge=True ) # 补充全局图例 g.add_legend() plt.show()
原理说明
catplot属于高层接口,会提前读取整个数据集的hue所有取值做全局计算,所有分面的偏移宽度统一按照全局hue类别数量分配,所以会出现空占位的问题。而手动通过FacetGrid逐分面调用barplot时,每次绘图只会读取当前分面的数据子集的hue取值,自动适配偏移宽度,符合预期效果。
内容的提问来源于stack exchange,提问作者ramslök
相关产品推荐
相关产品推荐

