0

I have built the following ggplot function but as you can see if you simply copy and run my code, the output plot has only 2 lines, not 3. I can't understand what the error is. Any suggestions? Many thanks

aa_ggplot_multiple_line_plot_from_df_columns <- function(df, x_col_name='', y_col_names=c(), show_example=F){
  
  if(show_example){
    df <- data.frame(YEAR = c(2000,2005,2010, 2015, 2020),
                     SALES_CARS = c(2.1,  2.4, 1.3, 2.9, 3.0),
                     SALES_BIKES = c(0.9,  1.1, 4.0, 2.3, 2.0),
                     SALES_HELM = c(4.1,  3.5, 3.4, 2.8, 1.2)
                     )
    
    x_col_name <- 'YEAR'
    y_col_names <- c('SALES_CARS', 'SALES_BIKES', 'SALES_HELM')
    
  }
  
  v_colors <- c('#000000', # black
                '#339933', # green
                '#1a75ff', #blue
                '#ff8c1a', #orange
                '#e60000', # red
                '#ffcc00', # yellow
                '#9900ff' #violet
                )
  
  y_col <- y_col_names[1]
  df[,y_col] <- as.numeric(df[,y_col])
  plt <- ggplot(data = df, aes(x = df[,x_col_name], y = df[,y_col] , group = 1   ) )+
            geom_line(color = v_colors[1], size = 1)  
  
  for(i in 2:length(y_col_names)){
      new_y_col <- y_col_names[i]
      df[,new_y_col] <- as.numeric(df[,new_y_col])
      
      plt <- plt +  geom_line(aes(y = df[,new_y_col], group = i    )
                              , color= v_colors[i]
                              , size = 1
                              #, linetype="twodash"
                    )   
  }
  
  return(plt)
}


plt <- aa_ggplot_multiple_line_plot_from_df_columns(df, x_col_name='', y_col_names=c(), show_example=T)
Angelo
  • 1,594
  • 5
  • 17
  • 50
  • 1
    You need to be careful with the lazy evaluation of `aes()` as described in the dup. One alternative would be to use `aes(y = .data[[!!new_y_col]], group = !!i)` inside your loop rather than `aes(y = df[,new_y_col], group = i)`. Or even better reshape the data into a long format as described in the accepted answer. – MrFlick Jun 29 '21 at 21:49
  • Understood. Many thanks for the help. Just so that I could dig more into it, where can I learn the reason why you added a dot "." in front of data? Thanks again – Angelo Jun 29 '21 at 21:59
  • 1
    Some discussion of the data pronoun can be found here: https://ggplot2.tidyverse.org/articles/ggplot2-in-packages.html?q=pronoun#using-aes-and-vars-in-a-package-function – MrFlick Jun 29 '21 at 22:05
  • 1
    I haven't figured out how to build flexibility around the `YEAR` as x-axis, but this code should work for any number of columns: `aa_ggplot_multiple_line_plot_from_df_columns <- function(df) { df %>% pivot_longer(-YEAR) %>% ggplot(aes(YEAR, value, color = name)) + geom_line() + scale_color_manual(values = v_colors) }` – Jon Spring Jun 29 '21 at 22:06

0 Answers0