Seaborn:如何使用多个折线图制作子图? sns.relplot似乎不支持它?

问题描述 投票:0回答:1

seaborn文档区分了图级和轴级函数:https://seaborn.pydata.org/introduction.html#figure-level-and-axes-level-functions

我知道像sns.boxplot这样的函数可以将轴作为参数,因此可以在子图中使用。

但是sns.relplot()怎么样?有没有办法把它放到子图中?

更一般地说,有没有办法让seaborn在子图中生成线图?

例如,这不起作用:

fig,ax=plt.subplots(2)
sns.relplot(x,y, ax=ax[0])

因为relplot不将轴作为参数。

python matplotlib seaborn
1个回答
0
投票

那不是真的。您确实可以将轴对象传递给relplot。以下是最小的答案。这里的关键点是关闭relplot返回的空轴对象。然后你也可以使用ax[0]ax[1]为你的各个子图添加额外的曲线,就像你使用matplotlib一样。

import seaborn as sns
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2)

xdata = np.arange(50)

sns.set(style="ticks")
tips = sns.load_dataset("tips")
g1 = sns.relplot(x="total_bill", y="tip", hue="day", data=tips, ax=ax[0])
g2 = sns.relplot(x="total_bill", y="tip", hue="day", data=tips, ax=ax[1])

# Now you can add any curves to individual axis objects 
ax[0].plot(xdata, xdata/5) 

# You will have to close the additional empty figures returned by replot
plt.close(g1.fig)
plt.close(g2.fig) 
plt.tight_layout()

enter image description here

您也可以使用seaborn作为线图

import seaborn as sns
import numpy as np

x = np.linspace(0, 5, 100)
y = x**2

ax = sns.lineplot(x, y)
ax.set_xlabel('x-label')
ax.set_ylabel('y-label') 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.