gpt4 book ai didi

python - 在水平图中使用 seaborn pairplot 比较 1 个自变量与多个因变量

转载 作者:太空狗 更新时间:2023-10-29 20:43:35 24 4
gpt4 key购买 nike

pairplot seaborn 的函数允许绘制数据集中的成对关系。

根据文档(添加了突出显示):

By default, this function will create a grid of Axes such that each variable in data will by shared in the y-axis across a single row and in the x-axis across a single column. The diagonal Axes are treated differently, drawing a plot to show the univariate distribution of the data for the variable in that column.

It is also possible to show a subset of variables or plot different variables on the rows and columns.

我只能找到一个为行和列子集不同变量的示例,here (这是用 PairGrid 和 pairplot() 绘制成对关系 部分下的第 6 个图)。如您所见,它绘制了许多独立变量 (x_vars) 与同一个因变量 (y_vars) 的关系图,结果非常好。

我正在尝试做同样的事情,针对许多相关变量绘制单个自变量。

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

ages = np.random.gamma(6,3, size=50)
data = pd.DataFrame({"age": ages,
"weight": 80*ages**2/(ages**2+10**2)*np.random.normal(1,0.2,size=ages.shape),
"height": 1.80*ages**5/(ages**5+12**5)*np.random.normal(1,0.2,size=ages.shape),
"happiness": (1-ages*0.01*np.random.normal(1,0.3,size=ages.shape))})

pp = sns.pairplot(data=data,
x_vars=['age'],
y_vars=['weight', 'height', 'happiness'])

问题是子图是垂直排列的,我找不到改变它的方法。

enter image description here

我知道这样的话,平铺结构就不会那么整洁,因为 Y 轴应该在每个子图中都被标记。另外,我知道我可以用这样的东西手工生成绘图:

fig, axes = plt.subplots(ncols=3)
for i, yvar in enumerate(['weight', 'height', 'happiness']):
axes[i].scatter(data['age'],data[yvar])

不过,我正在学习使用seaborn,觉得界面很方便,所以我想知道有没有办法。此外,这个示例非常简单,但对于更复杂的数据集,seaborn 会为您处理更多的事情,这会使 raw-matplotlib 方法很快变得复杂得多(hue,开始)

最佳答案

您可以通过交换传递给 x_vars 和 y_vars 参数的变量名来实现您正在寻找的东西。因此,重新访问代码的 sns.pairplot 部分:

pp = sns.pairplot(data=data,
y_vars=['age'],
x_vars=['weight', 'height', 'happiness'])

请注意,我在这里所做的只是将 x_vars 换成 y_vars。这些图现在应该水平显示:

enter image description here

x 轴现在对于每个绘图都是唯一的,具有由 age 列确定的公共(public) y 轴。

关于python - 在水平图中使用 seaborn pairplot 比较 1 个自变量与多个因变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966494/

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