用水平p中的seaborn pairplot比较1个独立变量和多个因变量

2024-06-16 10:23:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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)与相同的单因变量(yvars)的对比图,结果非常好。

我也在试着用一个独立变量和多个相依变量作图。

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为您处理了更多的事情,这些事情会使原始matplotlib非常快地变得更加复杂(色调,开始)


Tags: oftheinimportagedatasizeas
1条回答
网友
1楼 · 发布于 2024-06-16 10:23:57

通过交换传递给x-vars和y-vars参数的变量名,可以实现所需的功能。因此,重新访问代码的sns.pairplot部分:

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

请注意,我在这里所做的只是用xúu vars替换yúu vars。绘图现在应水平显示:

enter image description here

x轴现在对于每个绘图都是唯一的,其公共y轴由年龄列确定。

相关问题 更多 >