叠加两个seaborn工厂

2024-09-30 10:38:45 发布

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

我在使用seaborn库时遇到了一些困难。在

一般的问题是,我想把所有的(背景数据)用灰色细线画出来,然后在上面用彩色的、更粗的线标出我们想要突出显示的数据。首先,我没有成功地将绘图中的两个数据集与FacetGrid结合起来;其次,我在使用zorder时遇到了问题。在

我用exercise数据集做了一个虚拟示例:

sns.set_style('whitegrid')
exercise = sns.load_dataset("exercise")
background = exercise.assign(idkind = lambda df: df['id'].astype(str)+df.kind.astype(str))
foreground = exercise.groupby(['kind','time']).mean().reset_index().rename(columns={'id':'idkind'})

到目前为止,我尝试过:

  1. factorplot+factorplot

画出两个factorplot,好像它是sns.pointplot两倍于this example的相似。由于数据的实验设置,我需要sns.factorplot。不简单地说,这两个情节是独立产生的。我基本上想把下面的图放在上面的图上。在

^{pr2}$

enter image description here

  1. factorplot+gmap.(factorplot)

因此,我尝试使用sns.factorplot,我认为它会在顶部产生一个FacetGrid和{}第二个sns.factorplot,使用一个设计和类别完全相同的新数据集。结果是,它没有使用相同的子图,而是创建了许多具有重复绘图的行。在

g=sns.factorplot(x="time", y="pulse", hue='idkind', col='kind', legend=False,color='lightgrey',data=background)
g.map(sns.factorplot, x="time", y="pulse",hue='idkind', col='kind', data=foreground)

enter image description here

  1. factorplot+g.map(pointplot)

g.map一种点图,它将整个数据集放在所有子图中,不考虑{}的设计。在

g=sns.factorplot(x="time", y="pulse", hue='idkind', col='kind', legend=False,color='lightgrey',data=background)
g.map(sns.pointplot,x="time", y="pulse", hue='idkind', col='kind', data=foreground,zorder='1000')

enter image description here


Tags: 数据mapdfdatatimecolhuepulse
1条回答
网友
1楼 · 发布于 2024-09-30 10:38:45

应该指出的是,对factorplot的每个调用都会创建自己的图形。因此,通常情况下,如果目标是要有一个图形,则不能多次调用factorplot。这就解释了为什么1。和2。根本无法工作。在

对于3,这也是我第一次尝试(除了zorder应该是一个数字,而不是字符串)。
然而,zorder似乎被忽略了,或者至少没有正确地传递给底层matplotlib函数。在

一个选项是手动设置zorder。下面的循环遍历背景图的所有艺术家,并将其zorder设置为1。它还将这些艺术家存储在一个列表中。 创建前景图之后,可以再次循环所有艺术家,并将zorder设置为不在先前存储列表中的艺术家的更高值。在

我在这里完全省略foreground,因为这似乎只是计算平均值,这将由pointplot自动完成。在

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style('whitegrid')
exercise = sns.load_dataset("exercise")
background = exercise.assign(idkind = lambda df: df['id'] \
                            .astype(str)+df.kind.astype(str))

g=sns.factorplot(x="time", y="pulse", hue='idkind', col='kind', 
                 legend=False,color='lightgrey',data=background)

backgroundartists = []
for ax in g.axes.flat:
    for l in ax.lines + ax.collections:
        l.set_zorder(1)
        backgroundartists.append(l)

g.map(sns.pointplot, "time", "pulse")

for ax in g.axes.flat:
    for l in ax.lines + ax.collections:
        if l not in backgroundartists:
            l.set_zorder(5)

plt.show()

enter image description here

相关问题 更多 >

    热门问题