Home > Software engineering >  Using ggplot with lapply does not show y labels
Using ggplot with lapply does not show y labels

Time:04-09

I have the following data:

library(dplyr)

countries <- c('Austria',   'Belgium',  'Bulgaria', 'Croatia',  'Republic of Cyprus')
year <- rep(2009:2022, length(countries))
country <- as.data.frame(rep(countries, length(2009:2022)))
country <- country[order(country$`rep(countries, length(2009:2022))`),]
df<- cbind.data.frame(country, year)
df$year <- as.numeric(df$year)

df <- df %>%
  group_by(country) %>% 
  mutate(n_obs = 1:n())
df <- df %>% group_by(country) %>% 
  mutate(gdp = rnorm(n = 1, mean = 3000, sd = 300)   20.64*n_obs,
         inflation = rnorm(n = 1, mean = 5, sd = 3)   1.23*n_obs)

I want to make line plots for gdp and inflation one by one like so:

ggplot(df, aes(x = year, y = inflation, color = country))   geom_line()
ggplot(df, aes(x = year, y = gdp, color = country))   geom_line()

However, in the real data, I have a lot of variables that I want to plot, and I was wondering how I could use lapply to achieve that. I tried the following code:

lapply(df[,c(4,5)], function(var)
                              ggplot(data = df, aes(x = year, y = var, color = country))
         geom_line()   labs(x = "year", y = var))

This works, but I cannot get the y variable label on the plot. Any help would be appreciated.

Regards

CodePudding user response:

You can use the following code:

lapply(names(df)[4:5], function(var)
  ggplot(data = df, aes(x = year, y = .data[[var]], color = country))
    geom_line()   ylab(var))

Output gdp:

enter image description here

Output inflation:

enter image description here

  • Related