You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Seaborn中使用FacetGrid调用displot报错:'FacetGrid'对象不可调用的解决咨询

修复Seaborn 2×2 displot绘制的报错问题

嘿,我来帮你搞定这个报错!你遇到的TypeError: 'FacetGrid' object is not callable,核心原因是你用错了FacetGrid.map()的用法——你直接把sns.displot()的执行结果(一个FacetGrid对象)传给了map(),但map()需要的是可调用的绘图函数(比如sns.kdeplot),不是已经跑完的函数输出。

给你两种靠谱的解决方案,选哪种都行:

方案一:直接用displot实现2×2布局(最简洁)

其实sns.displot本身就支持row和col参数,完全不用手动创建FacetGrid,一行代码就能搞定你要的2×2分布密度图:

import seaborn as sns
import pandas as pd

# 先构造你的DataFrame
df = pd.DataFrame({'Re': x, 'n': y, 'Type': tp, 'tg': tg, 'gt': gt})

# 直接用displot实现2×2的kde图布局
g = sns.displot(
    data=df,
    x='Re',
    y='n',
    hue='Type',
    kind='kde',
    log_scale=True,
    palette=customPalette,
    row='gt',  # 按gt分成两行
    col='tg',  # 按tg分成两列
    height=2.5,
    aspect=1.65,
    margin_titles=False
)

方案二:用FacetGrid搭配kdeplot(自定义性更强)

如果你一定要用FacetGrid来实现,记得搭配axes-level的绘图函数(比如sns.kdeplot,而不是figure-level的displot),用map_dataframe来传递参数:

import seaborn as sns
import pandas as pd

df = pd.DataFrame({'Re': x, 'n': y, 'Type': tp, 'tg': tg, 'gt': gt})

# 创建FacetGrid,把hue和调色板在这里统一设置
g = sns.FacetGrid(
    df,
    row='gt',
    col='tg',
    margin_titles=False,
    height=2.5,
    aspect=1.65,
    hue='Type',
    palette=customPalette
)

# 用map_dataframe调用kdeplot,传入x/y和其他参数
g.map_dataframe(
    sns.kdeplot,
    x='Re',
    y='n',
    log_scale=True
)

# 按需添加图例
g.add_legend()

两种方法都能实现你想要的2×2 KDE分布图,第一种是Seaborn推荐的简洁用法,第二种适合需要对每个子图做更精细自定义的场景。

内容的提问来源于stack exchange,提问作者Vaggelis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:17:38