【问题标题】:How to plot 2 seaborn lmplots side-by-side?如何并排绘制 2 个 seaborn lmplots?
【发布时间】:2016-01-08 02:06:56
【问题描述】:

在子图中绘制 2 个分布图或散点图效果很好:

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

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

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

有什么方法可以并排绘制这些图表类型?

【问题讨论】:

    标签: python matplotlib ipython seaborn


    【解决方案1】:

    你得到这个错误是因为 matplotlib 及其对象完全不知道 seaborn 函数。

    将您的轴对象(即ax1ax2)传递给seaborn.regplot,或者您可以跳过定义这些对象并使用seaborn.lmplotcol kwarg

    使用相同的导入,预定义轴并使用 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)
    

    使用 lmplot 需要您的 dataframe to be tidy。继续上面的代码:

    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)
    

    【讨论】:

    • 是否有另一种方法(同时)并排绘制 lmplot?就我而言,我不想将色调拆分为不同的子图,而是将这些 lmplot 本身放入彼此相邻的子图中。我找不到怎么做的方法..
    • @Ben 我不明白你的评论。您是否尝试从对 lmplot 的调用中删除 hue 参数?
    • 有没有办法将两个带有多个轴的 lmplots(不是 regplots)组合起来?例如,我有两个 1 行 4 列的 lmplots。我希望将它们组合成 2 行 x 4 列图
    • @XinNiu 合并您的数据集,并使用lmplot 中的row 参数
    【解决方案2】:

    如果使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-24
      • 2018-11-29
      • 2017-08-25
      • 2020-06-23
      • 2017-12-17
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多