How to insert a secondary x axis with ggplot using subtraction (age/year of event)

Solution 1:

I presume you want to show the Year of the event, so since Age reformulates Year in relation to 2022, converting it back would take the form ~ 2022 - ., where the . represents the underlying x value in your plot.

ggplot(df, aes(x = age)) + 
  geom_histogram(fill = "firebrick3", color = "white") + 
  scale_x_continuous(breaks = scales::breaks_pretty(0:160, n = 10), 
                     sec.axis = sec_axis(~ 2022 - ., name = "Year", 
                                         breaks = scales::breaks_width(20))) +
  labs(x = "Age (years)", y = "Count")

enter image description here