拿R来画画(七):全面掌握折线图

本文详细介绍了如何使用R语言中的ggplot2包绘制各种类型的折线图,包括单条折线、多条折线以及带有置信区间的折线图,并展示了如何调整线条样式、颜色和置信区间的表示方式。

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

一条折线

library(gcookbook)
library(ggplot2)
ggplot(BOD, aes(x = Time, y = demand)) + 
geom_line()

在这里插入图片描述

如果改成因子型变量,由于Time不包括6,X轴上也不会出现6,从5直接蹦到7。

ggplot(BOD, aes(x = factor(Time), y = demand, group = 1)) + 
geom_line()

在这里插入图片描述

控制Y轴从0开始

ggplot(BOD, aes(x = Time, y = demand)) + 
geom_line() + 
ylim(0, max(BOD$demand))

在这里插入图片描述

设置不同的线性

在这里插入图片描述

ggplot(BOD, aes(x = Time, y = demand)) + 
geom_line(linetype = 'dashed', size = 1, colour = 'blue')

在这里插入图片描述

点线图

ggplot(BOD, aes(x = factor(Time), y = demand, group = 1)) + 
geom_line() + 
geom_point()

在这里插入图片描述

多条折线

library(plyr)
# 取由不同的supp和dose构成的每一组数据对应的len的平均值
tg <- ddply(ToothGrowth, c('supp', 'dose'), summarise, length = mean(len))
# 将颜色映射给supp
ggplot(tg, aes(x = dose, y = length, colour = supp)) + 
geom_line()

在这里插入图片描述

# 将线型映射给supp
ggplot(tg, aes(x = dose, y = length, linetype = supp)) + 
geom_line()

在这里插入图片描述

大约有如下类型

# 将形状映射给supp
ggplot(tg, aes(x = dose, y = length, shape = supp)) + 
geom_line() + 
geom_point()

在这里插入图片描述

# 将填充色映射给supp7
ggplot(tg, aes(x = dose, y = length, fill = supp)) + 
geom_line() + 
# colour指的是边框颜色,默认是黑色
geom_point(size = 4, shape = 21, colour = 'white')

在这里插入图片描述

当shape取NA时,不显示点;当shape取单独一个字母时,显示为那个字母;当shape取.时,显示一个不随size增大的小点;其他情况下shape的取值在0到25,分别对应不同形状。

在这里插入图片描述

# 将数据标记点错开
# 将填充色映射给supp7
ggplot(tg, aes(x = dose, y = length, fill = supp)) + 
geom_line(position = position_dodge(0.1)) + 
geom_point(size = 4, shape = 21, position = position_dodge(0.1), colour = 'white') + 
# 手动设置颜色
scale_fill_manual(values = c('orange', 'lightgreen'))

在这里插入图片描述

带置信域的折线

# 提取伯克利温度的移动平均及其95%置信区间
clim <- subset(climate, Source == "Berkeley", select = c("Year", "Anomaly10y", "Unc10y"))
head(clim)
A data.frame: 6 × 3
YearAnomaly10yUnc10y
<dbl><dbl><dbl>
1800-0.4350.505
1801-0.4530.493
1802-0.4600.486
1803-0.4930.489
1804-0.5360.483
1805-0.5410.475
  • 阴影式置信域
ggplot(clim, aes(x = Year, y = Anomaly10y)) + 
# 指定置信域上下界及使用阴影的透明度,alpha越小越透明
geom_ribbon(aes(ymin = Anomaly10y-Unc10y,ymax = Anomaly10y+Unc10y), alpha = 0.2) + 
geom_line()

在这里插入图片描述

  • 虚线式置信域
ggplot(clim, aes(x = Year, y = Anomaly10y)) + 
geom_line(aes(y = Anomaly10y-Unc10y), colour = 'grey10', linetype = "dotted") + 
geom_line(aes(y = Anomaly10y+Unc10y), colour = 'grey10', linetype = "dotted") + 
geom_line()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

羊城迷鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值