如果使用lmplot 的目的是将hue 用于两组不同的变量,那么如果不进行一些调整,regplot 可能就不够用了。
为了在两个并排的图中使用 seaborn 的 lmplot hue 参数,一种可能的解决方案是:
def hue_regplot(data, x, y, hue, palette=None, **kwargs):
from matplotlib.cm import get_cmap
regplots = []
levels = data[hue].unique()
if palette is None:
default_colors = get_cmap('tab10')
palette = {k: default_colors(i) for i, k in enumerate(levels)}
for key in levels:
regplots.append(
sns.regplot(
x=x,
y=y,
data=data[data[hue] == key],
color=palette[key],
**kwargs
)
)
return regplots
此函数给出的结果类似于lmplot(带有hue 选项),但接受ax 参数,这是创建复合图形所必需的。
一个使用例子是
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
%matplotlib inline
rnd = np.random.default_rng(1234567890)
# create df
x = np.linspace(0, 2 * np.pi, 400)
df = pd.DataFrame({'x': x, 'y': np.sin(x ** 2),
'color1': rnd.integers(0,2, size=400), 'color2': rnd.integers(0,3, size=400)}) # color for exemplification
# Two subplots
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
# ax1.plot(df.x, df.y)
ax1.set_title('Sharing Y axis')
# ax2.scatter(df.x, df.y)
hue_regplot(data=df, x='x', y='y', hue='color1', ax=ax1)
hue_regplot(data=df, x='x', y='y', hue='color2', ax=ax2)
plt.show()
Regplots with Hue