Seaborn:如何使用多个折线图制作子图?sns.relplot 好像不支持? [英] Seaborn: how to make subplots with multiple line charts? sns.relplot doesn't seem to support it?
问题描述
seaborn 文档区分了图形级和轴级函数:
您也可以单独使用 seaborn
as
导入 seaborn 为 sns将 numpy 导入为 npx = np.linspace(0, 5, 100)y = x**2ax = sns.lineplot(x, y)ax.set_xlabel('x-label')ax.set_ylabel('y-label')
The seaborn documentation makes a distinction between figure-level and axes-level functions: https://seaborn.pydata.org/introduction.html#figure-level-and-axes-level-functions
I understand that functions like sns.boxplot can take an axis as argument, and can therefore be used within subplots.
But how about sns.relplot() ? Is there no way to put that into subplots?
More generally, is there any way to get seaborn to generate line plots within subplots?
For example, this doesn't work:
fig,ax=plt.subplots(2)
sns.relplot(x,y, ax=ax[0])
because relplot doesn't take axes as an argument.
Well that's not true. You can indeed pass axis objects to relplot
. Below is a minimal answer. The key point here is to close the empty axis objects returned by relplot
. You can then also use ax[0]
or ax[1]
to add additional curves to your individual subfigures just like you would do with 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()
You can also make line plot solely using seaborn
as
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')
这篇关于Seaborn:如何使用多个折线图制作子图?sns.relplot 好像不支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!