如何为Seaborn FacetGrid中的每个子图设置不同binwidth?
给Seaborn FacetGrid每个子图设置不同binwidth的解决方案
直接给g.map()传binwidth列表会报错,因为map()会把这个列表参数传给每一个子图的histplot,但histplot的binwidth只接受单个数值,自然会抛出类型错误。下面提供两种可行的实现方式:
方法一:用map_dataframe配合自定义函数
先建立分组(这里是day)和对应binwidth的映射关系,然后通过自定义函数根据当前子图的分组取值匹配对应的binwidth:
import seaborn as sns sns.set_theme(style="darkgrid") tips = sns.load_dataset("tips") # 建立每个day对应的binwidth映射 binwidth_map = {"Thur":1, "Fri":2, "Sat":3, "Sun":4} def plot_hist(data, x, **kwargs): # 获取当前子图对应的分组名称 day = data["day"].iloc[0] sns.histplot(data=data, x=x, binwidth=binwidth_map[day], **kwargs) g = sns.FacetGrid(tips, col="day", height=3.5, aspect=.65) g.map_dataframe(plot_hist, "total_bill")
方法二:遍历子图axes和分组数据手动绘制
直接遍历FacetGrid的axes.flat和groupby后的数据集,逐个绘制histplot:
import seaborn as sns sns.set_theme(style="darkgrid") tips = sns.load_dataset("tips") binwidths = [1,2,3,4] # 按day分组,确保顺序和FacetGrid的子图顺序一致 grouped = tips.groupby("day") g = sns.FacetGrid(tips, col="day", height=3.5, aspect=.65) # 遍历每个子图轴、分组数据和对应的binwidth for ax, (day, data), bw in zip(g.axes.flat, grouped, binwidths): sns.histplot(data=data, x="total_bill", binwidth=bw, ax=ax)
这两种方法都能实现给每个子图设置不同的binwidth,你可以根据自己的习惯选择。
内容的提问来源于stack exchange,提问作者Quinten
相关产品推荐
相关产品推荐

