繁体   English   中英

几个简单的线性回归图

[英]Several simple linear regression plotting

我使用pima数据集来可视化x轴上的预测变量三头肌与三个响应变量中的每一个之间的线性关系: 怀孕葡萄糖 ,y轴上的压力在单独的图中。

这是我的代码:

library(pdp)
library(ggplot2)

pima=na.omit(pima)
head(pima)

lin1=lm(triceps~pregnant, data=pima)
coef=coef(lin1)

#plot1
p1=ggplot(data = pima, aes(pima$pregnant, pima$triceps))+
  geom_point()+
  geom_abline(col="blue",intercept = coef[1], slope = coef[2], size=1)+
  labs(title="Linear Regression", x="Pregnant", y="Triceps")+
  theme(plot.title = element_text(hjust = 0.5))

lin2=lm(triceps~glucose, data=pima)
coef=coef(lin2)

#plot2
p2=ggplot(data = pima, aes(pima$glucose, pima$triceps))+
  geom_point()+
  geom_abline(col="blue",intercept = coef[1], slope = coef[2], size=1)+
  labs(title="Linear Regression", x="Glucose", y="Triceps")+
  theme(plot.title = element_text(hjust = 0.5))

lin3=lm(triceps~pressure, data=pima)
coef=coef(lin3)

#plot3
p3=ggplot(data = pima, aes(pima$pressure, pima$triceps))+
  geom_point()+
  geom_abline(col="blue",intercept = coef[1], slope = coef[2], size=1)+
  labs(title="Linear Regression", x="Pressure", y="Triceps")+
  theme(plot.title = element_text(hjust = 0.5))

grid.arrange(p1, p2, p3, ncol=2)

不幸的是,该代码以不同的功能重复了三遍。 如果要针对x( 肱三头肌 )绘制所有特征,则必须一直复制和粘贴相同的代码,然后更改特征。 有没有更简单的方法可以做到这一点?

这是情节: 在此处输入图片说明

你当然可以。 使用facet_wrap 棘手的部分是从宽格式到长格式获取所需的数据。 对于您的情况,我使用gather

library(pdp)
library(ggplot2)
library(tidyr)

pima$id <- 1:nrow(pima)

xy <- pima[, c("triceps", "pregnant", "glucose", "pressure", "id")]

xy <- gather(xy, key = state, value = value, glucose, pregnant, pressure, -id, -triceps)

ggplot(xy, aes(x = value, y = triceps)) +
  theme_bw() +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  facet_wrap(~ state, scales = "free_x", ncol = 2)

在此处输入图片说明

我认为您在变量之间混在一起。 在内容中,您在x轴上使用三头肌 ,但在绘图中,您将其放在y轴中。 如果您想在x轴上绘制肱三头肌,在y轴上绘制孕妇血糖,压力,则此代码将帮助您:

library(pdp)
library(ggplot2)
pima=na.omit(pima)
head(pima)

pima %>%
 select(pregnant, glucose, pressure, triceps) %>%
 melt(id.vars = "triceps") %>%
 ggplot(aes(x = triceps, y = value)) + geom_point() + 
 geom_smooth(method = "lm") +
 facet_grid(~variable, scales = "free_x")

地块

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM