1

我一直在玩 Seaborn 中的这个绘图示例。

但是,我对标签绘图功能有点困惑:

def label(x, color, label):
    ax = plt.gca()
    ax.text(0, .2, label, fontweight="bold", color=color,
            ha="left", va="center", transform=ax.transAxes)


g.map(label, "x")

我假设分面网格映射函数 ( g.map) 使用参数 x 调用标签函数。但是,在函数内,不使用 x,仅使用label. 如果 map 函数没有传递其他参数,该函数如何知道它们是什么?

我显然错过了一些东西,所以任何帮助将不胜感激。

4

1 回答 1

1

从调用签名的seaborn.FacetGrid定义是mapFacetGrid.map

def map(self, func, *args, **kwargs):
    """ 
    ...
    args : strings
            Column names in self.data that identify variables with data to
            plot. The data for each variable is passed to `func` in the
            order the variables are specified in the call.
    ... 
    """

所以假设g是类型seaborn.FacetGrid- 我们用这条线确认

g = sns.FacetGrid(df, row="g", hue="g", aspect=15, height=.5, palette=pal)

链接的示例中

然后当你打电话

g.map(label, "x")

"x"self.data被解释为(df["x"]在这种情况下) 中的一列。函数中是否使用此数据无关紧要:调用签名要求其存在。


编辑

传递给 in 参数的值来自labelsource的这一部分funcg.map

def map(self, func, *args, **kwargs):
    # ...
    # Insert a label in the keyword arguments for the legend
    if self._hue_var is not None:
        kwargs["label"] = utils.to_utf8(self.hue_names[hue_k])
    # ...

基本上,这hue从每个获取名称datasubset并将其传递给label关键字参数,然后将其传递给绘图函数:

    # ...
    # Draw the plot
    self._facet_plot(func, ax, plot_args, kwargs)
    # ...

最终调用func传入的函数g.map

def _facet_plot(self, func, ax, plot_args, plot_kwargs):
    # ...
    func(*plot_args, **plot_kwargs)
    # ...

所以label参数来自于指定df["g"]为该hue行中的参数

g = sns.FacetGrid(df, row="g", hue="g", aspect=15, height=.5, palette=pal)
于 2020-01-16T04:36:59.000 回答