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不将轴作为参数。
那不是真的。您确实可以将轴对象传递给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()
您也可以使用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')