第8章 统计模型图
统计模型用于描述一个或多个解释变量与响应变量之间的关系,图形有助于可视化变量间关系。在本节中,我们将重点关注具有单个响应变量的模型,该变量可以是定量或定性变量。
8.1 相关图
相关图通过使用颜色或阴影显示其相关性,帮助您可视化一组定量变量之间的成对关系。
考虑Saratoga Houses
数据集,其中包含2006年SaratogaCounty
,NY住宅的销售价格
和特征
。为了探索定量变量之间的关系,我们可以计算Pearson相关系数
。
data(SaratogaHouses, package="mosaicData")
# select numeric variables
df <- dplyr::select_if(SaratogaHouses, is.numeric)
# calulate the correlations
r <- cor(df, use="complete.obs")
round(r,2)
price lotSize age landValue livingArea pctCollege bedrooms fireplaces bathrooms rooms
price 1.00 0.16 -0.19 0.58 0.71 0.20 0.40 0.38 0.60 0.53
lotSize 0.16 1.00 -0.02 0.06 0.16 -0.03 0.11 0.09 0.08 0.14
age -0.19 -0.02 1.00 -0.02 -0.17 -0.04 0.03 -0.17 -0.36 -0.08
landValue 0.58 0.06 -0.02 1.00 0.42 0.23 0.20 0.21 0.30 0.30
livingArea 0.71 0.16 -0.17 0.42 1.00 0.21 0.66 0.47 0.72 0.73
pctCollege 0.20 -0.03 -0.04 0.23 0.21 1.00 0.16 0.25 0.18 0.16
bedrooms 0.40 0.11 0.03 0.20 0.66 0.16 1.00 0.28 0.46 0.67
fireplaces 0.38 0.09 -0.17 0.21 0.47 0.25 0.28 1.00 0.44 0.32
bathrooms 0.60 0.08 -0.36 0.30 0.72 0.18 0.46 0.44 1.00 0.52
rooms 0.53 0.14 -0.08 0.30 0.73 0.16 0.67 0.32 0.52 1.00
ggcorrplot包
中的ggcorrplot函数
可用于可视化变量间的相关性。默认情况下,它会创建一个ggplot2图表,
深红色表示更强的正相关,深蓝色表示更强的负相关,白色表示没有相关性。
library(ggplot2)
# install.packages("ggcorrplot")
library(ggcorrplot)
ggcorrplot(r)
图8.1:相关矩阵
该ggcorrplot功能
有许多用于自定义输出的选项。例如
hc.order = TRUE
重新排序变量,将具有相似相关模式的变量放在一起。type = "lower"
绘制相关矩阵的下半部分。lab = TRUE
在图上叠加相关系数(如文本)。
ggcorrplot(r,
hc.order = TRUE,
type = "lower",
lab = TRUE)
图8.2:按选项排序的下三角相关矩阵
8.2 线性回归
线性回归允许我们探索响应变量和解释变量之间的关系。
考虑Saratoga数据集中的房价预测,变量有:地块大小(平方英尺)、年龄(年份)、土地价值(1000美元)、居住面积(平方英尺)、卧室和浴室的数量以及房子是否位于海滨等。