在本教程中,您将学习如何创建高级 散点图 。
设置笔记本
像往常一样,我们从设置编码环境开始。
import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
print("Setup Complete")
Setup Complete
加载并检查数据
我们将使用一个(伪造的)保险费用数据集,看看我们是否能够理解为什么一些客户比其他客户支付更多的费用。
如果你愿意,你可以在这里阅读更多有关数据集的。
# Path of the file to read
insurance_filepath = "../input/insurance.csv"
# Read the file into a variable insurance_data
insurance_data = pd.read_csv(insurance_filepath)
像往常一样,我们通过打印前五行来检查数据集是否正确加载。
insurance_data.head()
age | sex | bmi | children | smoker | region | charges | |
---|---|---|---|---|---|---|---|
0 | 19 | female | 27.900 | 0 | yes | southwest | 16884.92400 |
1 | 18 | male | 33.770 | 1 | no | southeast | 1725.55230 |
2 | 28 | male | 33.000 | 3 | no | southeast | 4449.46200 |
3 | 33 | male | 22.705 | 0 | no | northwest | 21984.47061 |
4 | 32 | male | 28.880 | 0 | no | northwest | 3866.85520 |
散点图绘制
为了创建一个简单的 散点图 ,我们使用 sns.scatterplot
命令并指定以下值:
- 水平的 x 轴(
x=insurance_data['bmi']
) ,以及 - 垂直 y 轴(
y=insurance_data['charges']
)。
sns.scatterplot(x=insurance_data['bmi'], y=insurance_data['charges'])
上面的散点图表明,身体质量指数(BMI)和保险费用呈 正相关 ,BMI 较高的客户通常也倾向于支付更多的保险费用。( 这种模式是有意义的,因为高体重指数通常与较高的慢性病风险相关。)
为了再次检查这种关系的强度,您可能需要添加一条 回归线 ,或者最拟合数据的线。我们通过将命令更改为sns.regplot
来完成此操作。
sns.regplot(x=insurance_data['bmi'], y=insurance_data['charges'])
颜色编码散点图
我们可以使用散点图来显示( 不是两个,而是... )三个变量之间的关系!实现这一点的一种方法是对这些点进行颜色编码。
例如,为了理解吸烟如何影响 BMI 和保险费用之间的关系,我们可以用'smoker'
对这些点进行彩色编码,并在轴上绘制其他两列('bmi'
, 'charges'
)。
sns.scatterplot(x=insurance_data['bmi'], y=insurance_data['charges'], hue=insurance_data['smoker'])
这个散点图显示,随着体重指数的增加,非吸烟者支付的费用往往略高一些,而吸烟者支付的费用则高得多。
为了进一步强调这一事实,我们可以使用 sns.lmplot
命令添加两个回归线,分别对应于吸烟者和非吸烟者。( 你会注意到吸烟者的回归线相对于不吸烟者的回归线有一个更陡峭的斜率! )
sns.lmplot(x="bmi", y="charges", hue="smoker", data=insurance_data)
上面的sns.lmplot
命令与你所学过的命令略有不同:
- 我们不是设置
x=insurance_data['bmi']
来选择insurance_data
中的'bmi'
列,而是设置x="bmi"
仅指定列名。 - 同样,
y="charges"
和hue="smoker"
也包含列名。 - 我们使用
data=insurance_data
来指定数据集。
最后,还有一种图表类型,可能与你习惯看到的散点图略有不同。通常,我们使用散点图来突出两个连续变量(如"bmi"
和"charges"
)之间的关系。但是,我们可以调整散点图的设计,以在其中一个主轴上呈现分类变量(如"smoker"
)。我们将这种图表类型称为分类散点图,并使用sns.swarmplot
命令创建它。
sns.swarmplot(x=insurance_data['smoker'],
y=insurance_data['charges'])
除此之外,这个章节告诉我们:
- 平均而言,不吸烟者的收费要低于吸烟者
- 支付最多的顾客是吸烟者; 而支付最少的顾客是不吸烟者。
标题:Kaggle数据可视化(四)散点图
作者:Departure
地址:https://www.unreachablecity.club/articles/2023/04/20/1682050920086.html
Comments | 0 条评论