Search code examples
rfor-loopggplot2global-variablesbold

put the global variable(here is 'var') in the bolditalic string in ggtitle of ggplot using for loop


reference : How to use bold, italic and underline in ggplot2

Hi, I want to put the global variable(here is 'var') in the bolditalic string in ggtitle of ggplot using for loop.

The graph doesn't have a value corresponding to 'var', it just comes out as 'var'.

a <- data.frame(date = 1:5, co2 = 11:15, year = 2021:2025) 
var = 2021
for (var in 2021:2025) {
    print(
        a %>% 
            filter(year == var) %>% 
            ggplot(aes(date, co2)) +
            geom_point() +
            ggtitle(expression(paste(
                bolditalic(var),
                bolditalic("KOR CO2"))))
    )
}

I want graph titles to be 2021 KOR CO2, 2022 KOR CO2, ..., 2025 KOR CO2.

Can you please solve this problem?


Solution

  • In addition to MrFlick's solution: ggplot offers automated subsetting and plotting data by one or two grouping variables. You can achieve such facetted plots conveniently with facet_wrap and facet_grid. In your case:

    a %>%
        ggplot(aes(date, co2)) +
        geom_point() +
        facet_wrap(~ year)