使用Seaborn的FacetGrid自定义注释

2024-05-12 06:02:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用Python中的Seaborn模块定制一些图形,但是我没有成功地创建自定义标签或注释。我有一些生成下图的代码:

plot = sns.FacetGrid(data = data, col = 'bot', margin_titles = True).set_titles('Human', 'Bot')
bins = np.linspace(0, 2000, 15)
plot = plot.map(plt.hist, 'friends_count', color = 'black', lw = 0, bins = bins)
plot.set_axis_labels('Number Following', 'Count')
sns.despine(left = True, bottom = True)

enter image description here

我想做两件事:1。用有意义的文本和2替换默认因子标签,例如“bot=0.0”。在每个类别后面的平均数处绘制垂直线。

下面是一个独立的示例:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'val': [1, 2, 2, 3, 3, 2, 1, 1, 2, 3], 'group': [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]})
plot = sns.FacetGrid(data = fake, col = 'group', margin_titles = True).set_titles('zero', 'one')
plot = plot.map(plt.hist, 'val', color = 'black', lw = 0)
sns.despine(left = True, bottom = True)

有人知道如何定制FacetGrids吗?


Tags: marginimporttruedataplotasbotplt
1条回答
网友
1楼 · 发布于 2024-05-12 06:02:16

关于set_titles的一些事情。

首先,默认标题是在FacetGrid.map方法中绘制的,因此如果要更改标题,必须在绘制之后调用set_titles,否则它们将被覆盖。

第二,如果您查看方法的docstring,它不只是获取标题的任意列表。它提供了一种使用列变量名称和值更改标题呈现方式的方法:

template : string
    Template for all titles with the formatting keys {col_var} and
    {col_name} (if using a `col` faceting variable) and/or {row_var}
    and {row_name} (if using a `row` faceting variable).

所以拥有“有意义的文本”最简单的方法就是在数据框中使用有意义的数据。以随机数据为例:

df = pd.DataFrame({'val': np.random.randn(100),
                   'group': np.repeat([0, 1], 50)})

如果您希望“group”是zeroone,您应该更改该列,或者创建一个新列:

df["group"] = df["group"].map({0: "zero", 1; "one"})

如果您不想在标题中包含变量名,那么使用FacetGrid.set_titles的正确方法是

g = sns.FacetGrid(data=df, col='group')
g.map(plt.hist, 'val', color='black', lw=0)
g.set_titles('{col_name}')

some bar graphs

如果不想更改正在打印的数据,则必须直接在matplotlib轴上设置属性,如下所示:

for ax, title in zip(g.axes.flat, ['zero', 'one']):
    ax.set_title(title)

请注意,这比上面的方法更不可取,因为您必须非常小心地确保列表的顺序是正确的,并且列表不会改变,而从数据帧本身获取信息将更加可靠。

要绘制平均值,需要创建一个可以传递给FacetGrid.map的小函数。在教程中有multiple examples关于如何做到这一点。在这种情况下,很容易:

def vertical_mean_line(x, **kwargs):
    plt.axvline(x.mean(), **kwargs)

然后你只需要重新绘制:

g = sns.FacetGrid(data=df, col='group')
g.map(plt.hist, 'val', color='black', lw=0)
g.map(vertical_mean_line, 'val')
g.set_titles('{col_name}')

some more bar graphs

相关问题 更多 >