Search code examples
rggplot2data-visualization

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


I have a data set with 1000 rows with a column given the year each event happened. My goal was to generate a histogram of age and then put a secondary x-axis on the plot with the year of each event. However, every example of a secondary axis that I find uses either addition or multiplication for the transformation; I can't seem to figure out how to get subtraction in there. The oldest event is in 1872.

Here's my code:

df <- df %>% mutate(age = 2022 - Year)

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

The histogram is correct; the regular x- and y-axes are correct, and the color is fine. The secondary x-axis is close, but it needs to be going backwards; as age increases from left to right, the year the event happens should be decreasing from left to right.

How is this done?


Solution

  • 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