0

I'm trying to loop ggplot to save them to a list. I have a problem since all the graphs appear to me with the data of the last variable. Can you help me please? I would like to have the graphics stored in a list

this is what my data looks like:

head(rev_regions1m)
         World           US      Eurozone Emerging.Markets Asia.Pacific.Ex.Japon       date
1 -0.015025440 -0.004314109 -0.0074216799     -0.016600603          -0.020172773 2018-12-31
2 -0.015025440 -0.004314109 -0.0074216799     -0.016600603          -0.020172773 2019-01-01
3 -0.015025440 -0.004314109 -0.0074216799     -0.016600603          -0.020172773 2019-01-02
4  0.016668433  0.001509360 -0.0007849854     -0.003445408          -0.007896815 2019-01-03
5  0.016668433  0.001509360 -0.0007849854     -0.003445408          -0.007896815 2019-01-04
6 -0.009066019 -0.005461343 -0.0051865009     -0.013999017          -0.016930263 2019-01-07
> 

this is the code i have:

plot<-list()
for (i in 1:(length(rev_regions1m)-1)) {
  plot[[i]]<-ggplot(rev_regions1m)+
    geom_line((aes(x=date, y= rev_regions1m[,i])),size=1.4, color="midnightblue", inherit.aes = FALSE)+
    labs(x="Date", y="Value", title = "Revisions 1M", subtitle = names_regions[i])+
    theme_wsj()+ 
    scale_colour_wsj("colors6")
}

Could anyone help me, please!

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
GFHR
  • 11
  • 1
  • 1
    Hello and welcome to StackOverflow :) In order for us to help you, please provide a [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) example. For example, to produce a minimal data set, you can use `head()`, `subset()`. **Then use `dput()`** to give us something that can be put in R immediately. Alternatively, you can use base R datasets such as `mtcars`, `iris`, *etc*. – Paul Aug 19 '20 at 06:15
  • try replacing `aes(x=date, y= rev_regions1m[,i])` with `aes_string("date", names(rev_regions1m)[i])` – det Aug 19 '20 at 06:34
  • thank you very much, it already worked!! – GFHR Aug 19 '20 at 06:52

1 Answers1

1

Here is one solution to produce a list of ggplot objects. The workflow is the following:

  1. Split your data to get a list of dataframes adequate to make plots

  2. Create you custom plotting function

  3. Use lapply() to loop over your list of dataframes and create a list of ggplot objects.

library(ggplot2)
# using base R dataset iris
# Lets say you want to make a plot for each specie and save it into a list
# split your initial data into pieces that will be used to make plots
iris_list = split(iris, iris$Species) 
# create a custom function that take as input a piece of your data
plot_fun = function(irisdf) {
  ggplot(irisdf, aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point()
}
# use lapply() on the list of pieces to get a list of ggplot objects
plots_list = lapply(iris_list, FUN = plot_fun)
Paul
  • 2,850
  • 1
  • 12
  • 37