Skip to main content
 首页 » 编程设计

R语言ggplot2 画线性回归图

2022年07月19日171傻小

本介绍如何使用R 可视化库 ggplot2 画拟合的线性回归模型。

语法

# ggplot(data,aes(x, y)) + 
#   geom_point() + 
#   geom_smooth(method='lm') 

语法基本格式,其中还包括一些参数后面示例会涉及。

1. 简单示例

下面通过几个示例进行说明。

#create dataset 
data <- data.frame(y=c(6, 7, 7, 9, 12, 13, 13, 15, 16, 19, 22, 23, 23, 25, 26), 
                   x=c(1, 2, 2, 3, 4, 4, 5, 6, 6, 8, 9, 9, 11, 12, 12)) 
 
#fit linear regression model to dataset and view model summary 
model <- lm(y~x, data=data) 
summary(model) 
 
library(ggplot2) 
 
ggplot(data, mapping = aes(x, y)) + geom_point() +  
  geom_smooth(mothod="lm", se=FALSE ) 

在这里插入图片描述

se=FALSE 表示不显示置信区间,默认显示。

下面示例增加了一些主题样式:

#create regression plot with customized style 
ggplot(data,aes(x, y)) + 
  geom_point() + 
  geom_smooth(method='lm', se=FALSE, color='turquoise4') + 
  theme_minimal() + 
  labs(x='X Values', y='Y Values', title='Linear Regression Plot') + 
  theme(plot.title = element_text(hjust=0.5, size=20, face='bold'))  

在这里插入图片描述

2. 实际示例

mpg 是ggplot2包提供38种流行品牌汽车燃油消耗数据.
hwy :highway miles per gallon (每加仑英里数)
drv : the type of drive train, where f=front-wheel drive, r=rear wheel drive, 4=4wd
displ : engine displacement, in litres(发动机排量,以升为单位)
class : “type” of car (汽车类型)

我们还可以在geom_smooth中增加过滤条件:

ggplot(data = mpg,  mapping = aes(x = displ,  y = hwy)) + 
  geom_point(mapping = aes(color = class)) + 
  geom_smooth(data = filter(mpg,  class == "subcompact"),se = FALSE ) 

每种类型的点使用不同颜色。
在这里插入图片描述

下面示例对比不同驱动类型的趋势拟合情况,使用facet_wrap可以一次性画多个图进行对比:

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ,  y = hwy)) + 
  geom_smooth(mapping = aes(x = displ, y = hwy, color=drv)) + 
  facet_wrap(~ drv,  nrow = 1) 

在这里插入图片描述


本文参考链接:https://blog.csdn.net/neweastsun/article/details/121017103
阅读延展