GFHR
GFHR

Reputation: 11

I've tried to do a loop in ggplot saving the results to a list

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!

Upvotes: 0

Views: 51

Answers (1)

Paul
Paul

Reputation: 2977

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)

Upvotes: 1

Related Questions