gpt4 book ai didi

python - 如何并排绘制 2 个 seaborn lmplots?

转载 作者:太空狗 更新时间:2023-10-29 17:01:37 26 4
gpt4 key购买 nike

在子图中绘制 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()

Subplot example

但是当我对 lmplot 而不是其他类型的图表执行相同操作时,我收到错误消息:

AttributeError: 'AxesSubplot' object has no attribute 'lmplot'

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

最佳答案

您会收到该错误,因为 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)

enter image description here

使用 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)

enter image description here

关于python - 如何并排绘制 2 个 seaborn lmplots?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33049884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com