首页 > 解决方案 > 有没有办法修改传递给 seaborn 中 facetgrid 的数据框?

问题描述

我想在 facetgrid 中绘制不同的图层,如下所示:

grid = sns.FacetGrid(data=tips, row='time', col='sex')
grid.map_dataframe(sns.lineplot, x="total_bill", y="tip", hue="smoker")
grid.map_dataframe(sns.scatterplot, x="total_bill", y="tip", hue="smoker")
#.
#.
#.
# n number of plots

在上面的示例中,线图和散点图都使用相同的数据框提示。现在,我想为不同的图更改数据框中的行,如下所示:

tips = tips.head(n) # n is any number

因此,对于一个图,我可能有 120 行数据,而对于另一个图,我将有 50 行,依此类推。

有什么办法可以做到这一点?

标签: pythonpandasdataframematplotlibseaborn

解决方案


您可以做的一件事是将绘图函数包装在 UDF 周围,然后将该函数与相应的参数一起传递给map_dataframe

def my_plot_func(data, plot_func, num_rows, *args, **kwargs):
    plot_func(data=data.head(num_rows), *args, **kwargs)

grid = sns.FacetGrid(data=tips, row='time', col='sex')
grid.map_dataframe(my_plot_func, plot_func=sns.lineplot, num_rows=10, 
                   x="total_bill", y="tip", hue="smoker")
grid.map_dataframe(my_plot_func, plot_func=sns.scatterplot, num_rows=5,
                   x="total_bill", y="tip", hue="smoker")

输出:

在此处输入图像描述


推荐阅读