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)