我试图在具有这些位置统计信息的图表顶部添加多个位置特定年份的累积值。下面是一个示例代码(取自对我之前的一个问题提出的解决方案)。
library(tidyverse)
library(lubridate)
library(dplyr)
library(tidyr)
mydate <- as.data.frame(seq(as.Date("2000-01-01"), to= as.Date("2019-12-31"), by="day"))
colnames(mydate) <- "Date"
Data <- data.frame(A = runif(7305,0,10),
J = runif(7305,0,8),
X = runif(7305,0,12),
Z = runif(7305,0,10))
DF <- data.frame(mydate, Data)
Data_Statistics <- DF %>% mutate(Year = year(Date), Month = month(Date)) %>%
pivot_longer(-c(Date,Year,Month), names_to = "variable", values_to = "values") %>%
filter(between(Month,5,10)) %>%
group_by(Year, variable) %>%
mutate(Cumulative = cumsum(values)) %>%
mutate(NewDate = ymd(paste("2020", Month,day(Date), sep = "-"))) %>%
ungroup() %>%
group_by(variable, NewDate) %>%
summarise(Median = median(Cumulative),
Maximum = max(Cumulative),
Minimum = min(Cumulative),
Upper = quantile(Cumulative,0.75),
Lower = quantile(Cumulative, 0.25))
我想提取年份
2019
的数据出Data_Statistics
,但是,没有做到 - 我不想要 2019 年的统计数据,而是我感兴趣的时期(5 月至 10 月,对应于 5 - 10 个月)的累计值 Data_2019 <- DF %>% mutate(Year = year(Date), Month = month(Date)) %>%
pivot_longer(-c(Date,Year,Month), names_to = "variable", values_to = "values") %>%
filter(between(Month,5,10)) %>%
filter(Year == 2019) %>%
group_by(Year, variable) %>%
mutate(Cumulative = cumsum(values))
绘制
Data_Statistics
使用 facet_wrap
ggplot
的功能下面的示例代码给了我附图。Data_Statistics %>% pivot_longer(cols = c(Median, Minimum,Maximum), names_to = "Statistic",values_to = "Value") %>%
ggplot(aes(x = NewDate))+
geom_ribbon(aes(ymin = Lower, ymax = Upper, fill = "Upper / Lower"), alpha =0.5)+
geom_line(aes(y = Value, color = Statistic, linetype = Statistic, size = Statistic))+
facet_wrap(~variable, scales = "free")+
scale_x_date(date_labels = "%b", date_breaks = "month", name = "Month")+
ylab("Daily Cumulative Precipitation (mm)")+
scale_size_manual(values = c(1.5,1,1.5))+
scale_linetype_manual(values = c("dashed","solid","dashed"))+
scale_color_manual(values = c("red","darkblue","black"))+
scale_fill_manual(values = "cyan", name = "")
我的终极目标
我想为各自的
facets
在图的顶部添加 2019 年的数据(即,另一个 geom_line)以查看我们与前几年的统计数据相比的情况。谢谢你。
最佳答案
如果你想用 2019 年的数据覆盖每个方面,你添加一个新的 geom_line
功能到您的 ggplot。在此之前,您需要像处理总数据一样首先操作 2019 年的数据:
Data_2019_plot <- Data_2019 %>%
pivot_longer(cols = c(Median, Minimum,Maximum), names_to = "Statistic",values_to = "Value")
现在在 ggplot 序列的末尾添加
+ geom_line(data = Data_2019_plot,
aes(y = Value, color = Statistic, linetype = Statistic, size = Statistic))
你会得到以下情节:
对于您的示例数据,2019 年的线条重叠很多,因此它们看起来不太清晰。您可能希望为 2019 设置特定颜色,而不是将其设置为美学映射。
关于r - 使用 R 中 ggplot 的 facet_wrap 功能在同一图上绘制多个图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60644191/