Home > Net >  How to combine multiple ggplots into one plot with same x and y axis
How to combine multiple ggplots into one plot with same x and y axis

Time:03-08

I want to combine multiple ggplots into one plot with same x and y axis. This is my enter image description here

library(ggplot2)
library(scales)

result <- read.csv("Downloads/Questions Trend - Questions Trend.csv")
result$Time_Formatted <- as.Date(result$Time_Formatted)
date_breaks <- as.Date(c("9/1/08", "5/12/14", "7/1/17", "2/2/19", "6/3/20"), "%m/%d/%y")
p1 <- ggplot(result, aes(result$Time_Formatted, result$A_Trnd))   
     geom_point(size = 0.1)   xlab("Month")   ylab("Temporal Trend")  
    scale_x_date(breaks = date_breaks , date_labels = "%Y-%m", limits = c(as.Date("2008-08-01"), as.Date("2021-08-01")))  
    theme(axis.text.x = element_text(angle = 70, vjust = 0.9, hjust = 1))
p1   geom_smooth(method = "loess", color = "red")

Now, I want to plot the same for Time vs B_Trnd, Time vs C_Trnd and have a combine plot like below.

enter image description here

How can I achieve this?

CodePudding user response:

library(tidyverse)
library(scales)
result <-read.csv("Downloads/Questions Trend - Questions Trend.csv") %>% 
  mutate(Time = as.Date(Time, format = "%m/%d/%y")) %>% 
  pivot_longer(cols = -Time, names_to = "group", values_to = "value") 
date_breaks <- as.Date(c("9/1/08", "5/12/14", "7/1/17", "2/2/19", "6/3/20"), "%m/%d/%y")
p1 <- ggplot(result, aes(Time, value))   
  geom_point(size = 0.1)   
  labs(x = "Month", y = "Temporal Trend")  
  scale_x_date(breaks = date_breaks , date_labels = "%Y-%m", limits = c(as.Date("2008-08-01"), as.Date("2021-08-01")))  
  theme(axis.text.x = element_text(angle = 70, vjust = 0.9, hjust = 1), 
 legend.position = "none")    
  geom_smooth(method = "loess", aes(color = group))  
  facet_wrap(vars(group), nrow = 1)
p1

enter image description here

  • Related