如何并排绘制2个seaborn lmplots?

sam*_*and 15 python matplotlib ipython seaborn

在子图中绘制2个distplots或散点图很有效:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
%matplotlib inline

# create df
x = np.linspace(0, 2 * np.pi, 400)
df = pd.DataFrame({'x': x, 'y': np.sin(x ** 2)})

# 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)

plt.show()
Run Code Online (Sandbox Code Playgroud)

子图示例

但是当我使用lmplot其他类型的图表而不是其他任何类型的图表时,我得到一个错误:

AttributeError:'AxesSubplot'对象没有属性'lmplot'

有没有办法将这些图表类型并排绘制?

Pau*_*l H 34

你得到那个错误,因为matplotlib及其对象完全没有意识到seaborn函数.

传递你的轴对象(即ax1和ax2),seaborn.regplot或者你可以跳过定义它们并使用colkwargseaborn.lmplot

使用相同的导入,预定义轴并使用regplot如下所示:

# create df
x = np.linspace(0, 2 * np.pi, 400)
df = pd.DataFrame({'x': x, 'y': np.sin(x ** 2)})
df.index.names = ['obs']
df.columns.names = ['vars']

idx = np.array(df.index.tolist(), dtype='float')  # make an array of x-values

# call regplot on each axes
fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)
sns.regplot(x=idx, y=df['x'], ax=ax1)
sns.regplot(x=idx, y=df['y'], ax=ax2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

使用lmplot需要您的数据帧整洁.继续上面的代码:

tidy = (
    df.stack() # pull the columns into row variables   
      .to_frame() # convert the resulting Series to a DataFrame
      .reset_index() # pull the resulting MultiIndex into the columns
      .rename(columns={0: 'val'}) # rename the unnamed column
)
sns.lmplot(x='obs', y='val', col='vars', hue='vars', data=tidy)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • (同时)还有另一种方法可以并排绘制 lmplot 吗?就我而言,我不想将色调分成不同的子图,而是将这些 lmplot 本身放入彼此相邻的子图中。我找不到办法如何做到这一点.. (2认同)
  • 有没有办法将两个 lmplot(不是 regplot)组合起来,每个都有多个轴?例如,我有两个 1 行 4 列的 lmplot。我希望将它们组合成 2 行 x 4 列图 (2认同)

RMS*_*RMS 8

如果使用的目的lmplot是用于hue两组不同的变量,那么regplot如果不进行一些调整可能还不够。为了lmplot hue在两个并排图中使用seaborn的论点,一种可能的解决方案是:

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
Run Code Online (Sandbox Code Playgroud)

此函数给出的结果类似于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()
Run Code Online (Sandbox Code Playgroud)

使用色调变量的正则图示例