Seaborn中FacetGrid.map和FacetGrid.map_dataframe有什么区别?

Jim*_*Jim 9 python seaborn facet-grid

Seaborn 文档对这些差异非常不清楚,我无法弄清楚它们。看起来它们的功能即使不完全相同,也非常相似。

\n

seaborn.FacetGrid.map

\n

seaborn.FacetGrid.map_dataframe

\n

具体有什么区别,什么时候使用其中一种?关于seaborn的文档map_dataframe说“与map方法不同,这里使用的函数必须\xe2\x80\x9cunderstand\xe2\x80\x9d Pandas对象”。这是map_dataframe 与map 文档中的唯一区别。如果不是数据帧,那么什么样的对象会被发送到地图中的函数,为什么它很重要?我也不太理解color目标函数必须接受的论点。该论证中包含哪些信息color

\n

Diz*_*ahi 6

当您使用 时FacetGrid.map(func, "col1", "col2", ...),该函数将传递列和func的值(如果需要,还可以传递更多值)作为参数 1 和 2(args[0]、args[1]、...)。此外,该函数始终接收一个名为 的关键字参数。"col1""col2"color=

当您使用 时FacetGrid.map_dataframe(func, "col1", "col2", ...),该函数func将传递名称"col1""col2"(如果需要,还可以传递更多)作为参数 1 和 2 (args[0], args[1], ...),并将过滤后的数据帧作为关键字参数data=。此外,该函数始终接收一个名为 的关键字参数color=

也许这个演示会有所帮助:

N=4
df = pd.DataFrame({'col1': np.random.random(N), 'col2':np.random.random(N), 'cat':np.random.choice([True,False], size=N)})

|    |     col1 |      col2 | cat   |
|---:|---------:|----------:|:------|
|  0 | 0.651592 | 0.631109  | True  |
|  1 | 0.981403 | 0.550882  | False |
|  2 | 0.467846 | 0.997084  | False |
|  3 | 0.119726 | 0.0452547 | False |
Run Code Online (Sandbox Code Playgroud)
  • 使用FacetGrid.map()

代码:

def test(*args, **kwargs):
    print(">>> content of ARGS:")
    print(args)
    print(">>> content of KWARGS:")
    print(kwargs)


g = sns.FacetGrid(df, col='cat')
g.map(test, 'col1', 'col2')
Run Code Online (Sandbox Code Playgroud)

输出:

>>> content of ARGS:
(1    0.981403
2    0.467846
3    0.119726
Name: col1, dtype: float64, 1    0.550882
2    0.997084
3    0.045255
Name: col2, dtype: float64)
>>> content of KWARGS:
{'color': (0.12156862745098039, 0.4666666666666667, 0.7058823529411765)}
>>> content of ARGS:
(0    0.651592
Name: col1, dtype: float64, 0    0.631109
Name: col2, dtype: float64)
>>> content of KWARGS:
{'color': (0.12156862745098039, 0.4666666666666667, 0.7058823529411765)}
Run Code Online (Sandbox Code Playgroud)
  • 使用map_dataframe

代码:

g.map_dataframe(test, 'col1', 'col2')
Run Code Online (Sandbox Code Playgroud)

输出:

>>> content of ARGS:
('col1', 'col2')
>>> content of KWARGS:
{'color': (0.12156862745098039, 0.4666666666666667, 0.7058823529411765), 
 'data':        col1      col2    cat
         1  0.981403  0.550882  False
         2  0.467846  0.997084  False
         3  0.119726  0.045255  False}
>>> content of ARGS:
('col1', 'col2')
>>> content of KWARGS:
{'color': (0.12156862745098039, 0.4666666666666667, 0.7058823529411765), 
 'data':        col1      col2   cat
         0  0.651592  0.631109  True}
Run Code Online (Sandbox Code Playgroud)