ggplot2 画线性回归图

本文详细介绍了如何使用R的ggplot2库创建线性回归图表,包括基本语法示例、定制风格和数据集mpg的应用实例,展示了如何根据变量、驱动类型进行趋势分析和可视化对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本介绍如何使用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)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值