使用R中的ggplot在子图中显示多个变量
下面的代码只为一个变量绘制多个子图,但我想创建多个子图,以便第一个子图在同一个图上具有前两个变量(Barnwell_obs和Barnwell_sim)。类似地,第二个子图应包含接下来的两个变量Breton_obs和Breton_sim,依此类推。因此,基本上,下面的数据将有两个子图。我的实际数据有40多列使用R中的ggplot在子图中显示多个变量,r,ggplot2,R,Ggplot2,下面的代码只为一个变量绘制多个子图,但我想创建多个子图,以便第一个子图在同一个图上具有前两个变量(Barnwell_obs和Barnwell_sim)。类似地,第二个子图应包含接下来的两个变量Breton_obs和Breton_sim,依此类推。因此,基本上,下面的数据将有两个子图。我的实际数据有40多列 # Loading libraries library(tidyverse) library(lubridate) df <- tribble( ~date, ~Barnwell
# Loading libraries
library(tidyverse)
library(lubridate)
df <- tribble(
~date, ~Barnwell_obs, ~Barnwell_sim, ~Breton_obs, ~Breton_sim,
"2013-01-01", 22.082, 90.86, 43.91, 110.36,
"2013-02-02", 24.094, 80.86, 53.878, 115.36,
"2013-03-03", 25.11, 80.86, 63.852, 120.36,
"2013-04-04", 22.214, 70.86, 63.828, 130.36,
"2013-05-05", 30.278, 70.86, 83.812, 140.36,
"2013-06-06", 38.48, 60.86, 93.794, 130.36,
"2013-07-07", 45.662, 70.86, 83.774, 130.36,
"2013-08-08", 55.948, 80.86, 73.75, 120.36,
"2013-09-09", 60.272, 91.14, 73.722, 120.36,
"2013-10-10", 60.892, 91.14, 83.702, 110.36)
# Some quick data preparation
long_df <- df %>%
mutate(date = ymd(date)) %>%
pivot_longer(-date, names_to = "stations", values_to = "values")
# Simplified code
ggplot(long_df, aes(x = date, y = values)) +
geom_line(size = 1) +
scale_x_date("Month",
date_breaks = "month",
date_labels = '%B') +
scale_y_continuous("Values", labels = function(x) paste0(x, "mm")) +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
facet_wrap(~ stations, ncol = 1)
#加载库
图书馆(tidyverse)
图书馆(lubridate)
df%
轴长(-date,name_to=“stations”,values_to=“values”)
#简化代码
ggplot(长距离df,aes(x=日期,y=值))+
几何尺寸线(尺寸=1)+
比例x日期(“月”,
date_breaks=“月”,
日期标签=“%B”)+
缩放y连续(“值”,标签=函数(x)粘贴0(x,“mm”))+
主题(axis.text.x=元素\文本(角度=45,hjust=1))+
面_包裹(~站,ncol=1)
pivot\u long
是灵活的,因此我们可以利用names\u sep
和names\u to
library(dplyr)
library(tidyr)
long_df <- df %>%
pivot_longer(cols = -date, names_to = c(".value", 'grp'), names_sep = "_")
库(dplyr)
图书馆(tidyr)
long_df%
pivot_longer(cols=-date,names_to=c(“.value”,“grp”),names_sep=“”)