R语言ggplot时间趋势图

本文介绍了如何在R语言中使用ggplot2及其相关库如patchwork、dplyr等生成数据、绘制基础线图、设置主题、线型和颜色,以及创建和拼接不同风格的图形,包括使用layout参数进行多图布局。
摘要由CSDN通过智能技术生成

1.载入相关package

library(patchwork)
library(dplyr)
library(ggplot2)
library(ggstatsplot)
library(ggpattern)
library(esquisse)
library(scales)

2.生成数据

set.seed(2016)
df <- expand.grid(c(2011:2020), c(1:5)) %>% 
  rename(year= Var1, id = Var2) %>% 
  mutate(value = runif(dim(df)[1], min = 0, max = 1))

3.画图

  • (1) 基本句式
f1<-ggplot(df, aes(x = year, y = value, color = factor(id))) + 
  geom_line(aes(linetype = factor(id)))

在这里插入图片描述

  • (2) 设置主题
f2<-ggplot(df, aes(x = year, y = value, color = factor(id))) + 
  geom_line(aes(linetype = factor(id))) +
  theme_bw()

在这里插入图片描述

  • (3) 设置line pattern
f3<-ggplot(df, aes(x = year, y = value, group = id, color = factor(id))) +
  geom_line(aes(linetype = factor(id)),color= "black") +
  labs(title = "Time Trend of Value by ID", x = "Year", y = "Value") +
  scale_linetype_manual(values = c("solid", "dashed", "dotted", "dotdash", "longdash"))+ 
  scale_x_continuous(breaks = seq(min(df$year), max(df$year), by = 1))+  # 将 x 轴刻度设置为间隔1年的整数年份
  theme_bw()+ 
  theme(plot.title = element_text(hjust = 0.5),    # 设置标题居中
        aspect.ratio = 15/35) 

在这里插入图片描述

  • (4) 设置颜```R
f4<-ggplot(df, aes(x = year, y = value, group = id, color = factor(id))) +
  geom_line(aes(linetype = factor(id))) +
  labs(title = "Time Trend of Value by ID", x = "Year", y = "Value") +
  scale_linetype_manual(values = c("solid", "dashed", "dotted", "dotdash", "longdash"))+ 
  scale_color_manual(values = c("red", "blue", "green", "orange", "purple")) +   #设置颜色
  scale_x_continuous(breaks = seq(min(df$year), max(df$year), by = 1))+
  theme_bw()+ 
  theme(plot.title = element_text(hjust = 0.5),    
        aspect.ratio = 15/35) 

在这里插入图片描述

4.拼图

  • (1)直接拼图
(f1 | f2) / (f3 | f4)

在这里插入图片描述

  • (2)设置layout格式
layout <- '
ABB
CDD
'
f1 + f2 + f3 + f4 + plot_layout(design = layout)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

mengke25

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

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

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

打赏作者

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

抵扣说明:

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

余额充值