0

I want to plot the 4 ggplot graph in a page and the 4 line in one graph within a loop. What I only can do now is the plot 4 graphs separately.

Is there any smart way to do it? thanks

library(ggplot2)


dataset1<-c(1,5,12,21,30,50,90,100)
dataset2<-c(10,15,120,210,300,50,90,100)
dataset3<-c(1,5,12,21,30,50,900,1000)
Date = c("2020/07/16","2020/07/23","2020/07/30","2020/08/06","2020/08/13","2020/08/20","2020/08/27","2020/09/13")

datatotal<-c(dataset1,dataset2,dataset3)
Groups<-3
datamatrix1<-matrix(datatotal,length(dataset1),Groups)

plot1g<-function(dataset)
{y<-dataset/10*dataset[1]
df <- data.frame(y, Date = as.Date(Date))
ggplot(df) + aes(Date, y) + geom_line()}



plot4g<-function(datamatrix)
{
  
  for(i in 1:dim(datamatrix)[2]) 
{
  print(plot1g(datamatrix[,i]))
  
}}
  
  
  
  
  

 
  
 plot4g(datamatrix1) 
AI Kidds
  • 29
  • 6

2 Answers2

1

As the other answer suggests, the "smart" way of doing this is to reshape your data into long format, but to answer your question you can define an empty ggplot object outside of your loop, and then add layers sequentially:

p <- ggplot()
for(i in 1:dim(datamatrix1)[2]) 
{
  y <- datamatrix1[,i]/(10*datamatrix1[1, i])
  df <- data.frame(y, Date = as.Date(Date))
  p <- p + geom_line(data = df, aes(Date, y), color = i)
}
p
Dij
  • 1,318
  • 1
  • 7
  • 13
0

If you restructure your data you can do it on one call to ggplot. Here's an example using tidyr::pivot_longer. I changed the data a bit to make the plot look more interesting.

library(ggplot2)
library(tidyr)

dataset1<-c(100,50,110,21,31,40,80,100)
dataset2<-c(10,15,120,22,30,50,90,100)
dataset3<-c(1,1,2,21,30,50,90,100)
Date <- as.Date(c("2020/07/16","2020/07/23","2020/07/30","2020/08/06","2020/08/13","2020/08/20","2020/08/27","2020/09/13"))

df <- data.frame(dataset1, dataset2, dataset3, Date, stringsAsFactors = F) %>% 
    pivot_longer(c(dataset1, dataset2, dataset3))

ggplot(data=df, aes(x=Date, y=value, col=name)) + geom_line()

enter image description here

Andrew Chisholm
  • 6,362
  • 2
  • 22
  • 41
  • Thanks. So if I want to plot my y in my code I need to store y in an three dimension array right? – AI Kidds Jan 21 '21 at 07:37
  • You need to convert from wide format to long format using `pivot_longer`. In my example, there are 4 columns in the wide format data and this reduces to 3 in long format but the number of rows increases to reflect the different combinations within the wide format data. – Andrew Chisholm Jan 21 '21 at 08:14