larmarange / ggstats

Extension to ggplot2 for plotting stats
https://larmarange.github.io/ggstats/
GNU General Public License v3.0
26 stars 1 forks source link

Question: geom_stripped_cols with dates on the x-axis. #52

Closed mooibroekd closed 7 months ago

mooibroekd commented 7 months ago

Hi,

Thanks for your excellent package that has helped me a lot in achieving what I wanted to plot. However, now I am stuck, I cannot get columns when using date as a x-axis, plotting monthly data. What am I doing wrong? I am assuming that plotting monthly data and using a width of 12 would shade each year.

library(openair)
library(ggstats)
library(ggplot2)

mydata <- openair::mydata

mydata |>
  openair::timeAverage(avg.time = "month") |> 
  ggplot2::ggplot(aes(date, nox)) +   
  ggplot2::geom_point() +   
  ggplot2::geom_line() +
  ggplot2::theme_minimal() +
  ggstats::geom_stripped_cols(width = 12)

Created on 2023-12-20 with reprex v2.0.2

larmarange commented 7 months ago

Hi,

your date column is of class "POSIXct". Therefore, it is internally stored as seconds. width should therefore be expressed in seconds.

If you convert it into the class Date, it will be stored as a number of days.

library(openair)
library(ggstats)
library(ggplot2)

mydata <- openair::mydata

d <- mydata |>
  openair::timeAverage(avg.time = "month")

class(d$date)
#> [1] "POSIXct" "POSIXt"

d |> 
  ggplot2::ggplot(aes(date, nox)) +   
  ggplot2::geom_point() +   
  ggplot2::geom_line() +
  ggplot2::theme_minimal() +
  ggstats::geom_stripped_cols(width = 365*24*60*60)


d$date2 <- as.Date(d$date)

d |> 
  ggplot2::ggplot(aes(date2, nox)) +   
  ggplot2::geom_point() +   
  ggplot2::geom_line() +
  ggplot2::theme_minimal() +
  ggstats::geom_stripped_cols(width = 365)

Created on 2023-12-21 with reprex v2.0.2

larmarange commented 7 months ago

You may need to adjust nudge_x if you want to grey full years.

library(openair)
library(ggstats)
library(ggplot2)

mydata <- openair::mydata

d <- mydata |>
  openair::timeAverage(avg.time = "month")

d$date2 <- as.Date(d$date)

d |> 
  ggplot2::ggplot(aes(date2, nox)) +   
  ggplot2::geom_point() +   
  ggplot2::geom_line() +
  ggplot2::theme_minimal() +
  ggstats::geom_stripped_cols(width = 365, nudge_x = 183)

Created on 2023-12-21 with reprex v2.0.2

mooibroekd commented 7 months ago

Great, thank you. The internal storage in seconds slipped my mind.

larmarange commented 7 months ago

Finally, for something clearer, you could re express the date in years.

library(openair)
library(ggstats)
library(ggplot2)

mydata <- openair::mydata

d <- mydata |>
  openair::timeAverage(avg.time = "month")

d$date2 <- lubridate::year(d$date) + (lubridate::month(d$date) - 1) / 12

d |> 
  ggplot2::ggplot(aes(date2, nox)) +   
  ggplot2::geom_point() +   
  ggplot2::geom_line() +
  ggplot2::theme_minimal() +
  ggstats::geom_stripped_cols(nudge_x = 0.5)

Created on 2023-12-21 with reprex v2.0.2