Home > database >  lapply function to create many plots in Ggplot
lapply function to create many plots in Ggplot

Time:11-17

I'm trying to plot the line graph for X=date Y=column which is XS1-XS10. I use the lapply with a next function

plot_data_column = function (column) {
    ggplot(data= excess_return, aes(y=column,x=date))  
        geom_line() 
        geom_hline(yintercept = mean(excess_return$column), color="red") 
        ggtitle(column) 
        theme_minimal()
}

and then use lapply to plug in the columns of the dataset into the ggplot.

ggplots = lapply(excess_return[,1:10], plot_data_column)

My problem occurs with geom_hline which doesn't recognize the column and ggtitle(column). P.s I have tried also like this

ggplots = lapply(colnames(excess_return[,1:10]), plot_data_column)

I wonder why R doesn't accept the XS1 as it were written manually by me? because this code perfectly works.

ggplot(data= excess_return, aes(y=XS1,x=date))  
        geom_line() 
        geom_hline(yintercept = mean(excess_return$XS1), color="red") 
        theme_minimal()

The only thing what i want to is to iterate the XS1 to XS10.

enter image description here

Thank you for support

CodePudding user response:

you can adapt this to your data strucutre:

plot_data_column = function (.data, .column) {
  ggplot2::ggplot(data= .data, ggplot2::aes(y=!!dplyr::sym(.column),x = Petal.Width))  
    ggplot2::geom_line()  
    ggplot2::geom_hline(yintercept = .data %>% 
                          dplyr::pull(!!dplyr::sym(.column)) %>% 
                          mean(), 
                        color="red") 
    ggplot2::ggtitle(.column)  
    ggplot2::theme_minimal()
}

plots <- names(iris)[1:3] %>% 
  purrr::map(~plot_data_column(.data = iris, .column = .x))

You need to change the names(iris)[1:3] to your names names(excess_return)[1:10] and x = Petal.Width to x = date.

  • Related