Home > Enterprise >  For Loop for ggplot2 in R
For Loop for ggplot2 in R

Time:08-18

I have this data frame where I want to create multiple plots at the same time in a loop, but when I run the code it gives me an error. Can anyone please tell me what I am doing wrong!

Data:

structure(list(Date = structure(c(289094400, 297043200, 304992000, 
312854400, 320716800, 328665600), tzone = "UTC", class = c("POSIXct", 
"POSIXt")), NORTH = c(4.06976744186047, 5.51675977653633, 7.2799470549305, 
4.75015422578655, 4.59363957597172, 3.15315315315317), YORKSANDTHEHUMBER = c(4.0121120363361, 
5.45851528384282, 9.52380952380951, 6.04914933837431, 3.03030303030299, 
5.42099192618225), NORTHWEST = c(6.57894736842105, 6.95256660168939, 
6.50060753341436, 5.5904164289789, 4.59211237169096, 4.70041322314051
), EASTMIDS = c(4.98489425981872, 8.20143884892085, 6.91489361702127, 
5.22388059701494, 5.61465721040189, 4.64465584778958), WESTMIDS = c(4.65838509316771, 
4.74777448071216, 8.66855524079319, 6.56934306569344, 3.22896281800389, 
3.17535545023698), EASTANGLIA = c(6.74525212835624, 8.58895705521476, 
8.47457627118643, 10.7291666666667, 4.8447789275635, 4.84522207267835
), OUTERSEAST = c(6.7110371602884, 7.53638253638255, 9.47317544707589, 
8.56512141280351, 3.82269215128102, 2.11515863689776), OUTERMET = c(4.54545454545458, 
6.58505698607005, 7.36633663366336, 7.08225746956843, 4.3747847054771, 
1.68316831683168), LONDON = c(8.11719500480309, 10.3065304309196, 
6.32299637535239, 7.65151515151515, 1.30190007037299, 2.1535255296978
), SOUTHWEST = c(6.17577197149644, 7.71812080536912, 7.63239875389407, 
9.45489628557649, 2.46804759806079, 2.19354838709679), WALES = c(6.09418282548476, 
8.35509138381203, 7.40963855421687, 7.01065619742007, 1.15303983228513, 
3.47150259067357), SCOTLAND = c(5.15222482435597, 4.12026726057908, 
5.40106951871658, 8.67579908675796, -0.280112044817908, 2.94943820224719
), NIRELAND = c(4.54545454545454, 4.94752623688156, 4.42857142857145, 
2.96397628818967, 6.06731620903454, 0.0835073068893502), UK = c(5.76890543055322, 
7.20302836425676, 7.39543442582184, 7.22885986848197, 3.23472252213347, 
2.95766398929048)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

Code:

for(i in 2:ncol(data2)) {  # Printing ggplot within for-loop
  print(ggplot(data2, aes(x = Date, y = data2[, i]))   # Basic ggplot2 plot of x & y's
          geom_line()  labs(title = "Uk States", 
                            y = "",
                            x = "")  theme_bw() 
          geom_hline(yintercept = 0))
  Sys.sleep(1)
}

Error:

Don't know how to automatically pick scale for object of type tbl_df/tbl/data.frame. Defaulting to continuous.
Error in is.finite(x) : default method not implemented for type 'list'

CodePudding user response:

I would suggest to loop over the column names instead of value. You may then use .data to use as y-index.

library(tidyverse)

for(i in names(data2)[-1]) {  # Printing ggplot within for-loop
  # Basic ggplot2 plot of x & y's
  print(ggplot(data2, aes(x = Date, y = .data[[i]]))   
          geom_line()  labs(title = "Uk States", 
                            y = "",
                            x = "")  
          theme_bw() 
          geom_hline(yintercept = 0))
  Sys.sleep(1)
}

You may also try facet_wrap to combine multiple plots together.

data2 %>%
  pivot_longer(cols = -Date) %>%
  ggplot(aes(Date, value))   
  geom_line()   facet_wrap(~name)   
  labs(title = "Uk States", x = "", y = "")  
  theme_bw()  
  geom_hline(yintercept = 0)

enter image description here

CodePudding user response:

Another way of generating ggplot in a loop is to use lapply, where we loop for colnames and use aes_string as the aesthetic mapping.

Here the results are saved to the list ggplot_list, where you can extract individual plot by indexing (e.g. plot for NORTH is stored in ggplot_list[[1]])

Note that I've changed labs(title = i) so that the plot title would be your column names.

library(ggplot2)

ggplot_list <- lapply(colnames(data2[-1]), \(i) {
  ggplot(data2, aes_string("Date", x))   
    geom_line()   
    labs(title = i, y = "", x = "")   
    theme_bw()  
    geom_hline(yintercept = 0)
})
  • Related