使用for循环将全局变量(这里是'var')放在ggplot的ggtitle中的粗体字符串中

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

参考:How to use bold, italic and underline in ggplot2

你好,我想把全局变量(这里是'var')放在粗体字串的ggtitle中ggplot 使用 for 循环。

该图没有对应 'var' 的值,它只是显示为 '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"))))
    )
}

我希望图表标题为 2021 KOR CO2, 2022 KOR CO2, ..., 2025 KOR CO2.

你能解决这个问题吗?

除了 MrFlick 的解决方案之外:ggplot 通过一个或两个分组变量提供自动子集和绘图数据。您可以使用 facet_wrapfacet_grid 方便地实现这样的 facetted 图。 在你的情况下:

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