jack-davison/ggopenair

Question: how to change ggplot output in trend_variation()?

mooibroekd opened this issue · 1 comments

Just like other {ggplot2} objects I would expect the trend_variation() function to be able to allow the plots to be styled. However, due to the nature the plots are constructed (patchwork) the following code does not work.

mydata <- openair::mydata

ggopenair::trend_variation(mydata = mydata,
                           pollutant = "nox") +
  ggplot2::theme_bw()

Created on 2023-11-19 with reprex v2.0.2

One can apply themes and other changes to individual plots in the {patchwork} output (although I am not sure if the code below is the way to go):

mydata <- openair::mydata

test <- ggopenair::trend_variation(mydata = mydata,
                                   pollutant = "nox") +
  ggplot2::theme_bw()

# this works
test[[1]] <- test[[1]] + ggplot2::theme_bw()
test[[2]] <- test[[2]] + ggplot2::theme_bw()

test # show changes

# this fails:
test[[3]] <- test[[3]] + ggplot2::theme_bw()
#> Error in `test[[3]]`:
#> ! Index out of bounds
#> Backtrace:
#>     ▆
#>  1. ├─test[[3]]
#>  2. └─patchwork:::`[[.patchwork`(test, 3)
#>  3.   └─cli::cli_abort("Index out of bounds")
#>  4.     └─rlang::abort(...)

Created on 2023-11-19 with reprex v2.0.2

It seems that I cannot access the two other plots, and therefore cannot apply styles to them. Now, this might be due to my not so optimal script, but the main question is: how would one apply their own {ggplot2} styles to each of the different plots?

Of minor concern are the changes in the layout of the plots compared to openair::timeVariation(), in which I prefer the month plot being in the center of the three panel plots on the latest row. And the documentation still references openair::timeVariation() in the Details section.

I was a little bored this evening, so I decided to solve my own question(s). It still can use some additional work, but that is mostly {ggplot2} stuff. ;-)

mydata <- openair::mydata

test <- ggopenair::trend_variation(mydata = mydata,
                                   pollutant = "nox") +
  ggplot2::theme_bw()

test

# test[[1]] is the first row and contains only one plot
test[[1]] <- test[[1]] + ggplot2::theme_bw()
# the second row contains three plots that need to be addressed individually
test[[2]][[1]] <- test[[2]][[1]] + ggplot2::theme_bw()
test[[2]][[2]] <- test[[2]][[2]] + ggplot2::theme_bw()
test[[2]][[3]] <- test[[2]][[3]] + ggplot2::theme_bw()

test

# openair has a slightly different layout for the last row. This can be
# easily replicated by swapping some patch areas:
openair::timeVariation(mydata = mydata,
                       pollutant = "nox")

# ggopenair replication:
tmp <- test[[2]][[2]]
test[[2]][[2]] <- test[[2]][[3]]
test[[2]][[3]] <- tmp
rm(tmp)

test

# and to finish it, make the height of the first row half the size of the
# second row.
test +
  patchwork::plot_layout(heights = c(1, 2))

Created on 2024-01-01 with reprex v2.0.2