Search code examples
rggplot2plot

Adding a second axis to a plot using ggplot2?


I have a graph here with Wavenumber as the primary x-axis. I have another column in my data table called Wavelength, that is a direct conversion from every data point in the Wavenumber column. Is there a way to put the Wavelength column on the top of the graph to have a secondary x-axis? Both Wavenumber and Wavelength will have the same amount of variables.

enter image description here

The conversion from Wavenumber to Wavelength is 1/Wavenumber, so I have this set up to add a new column to my existing data frame:

new_df_test <- new_df %>%
   mutate(Wavelength = 1 / Wavenumber)

This is what I have for the original plot.

ggplot(new_df_test, aes(x = Wavenumber, y = X2024.05.17T12.35.56)) + geom_line()

I have tried using sec_axis() in scale_x_continuous:

ggplot(new_df_test, aes(x = Wavenumber, y = X2024.05.17T12.35.56)) + geom_line() + scale_x_continuous(sec.axis = sec_axis(label = Wavelength))

but I get an error saying:

Error in `sec_axis()`:
! Can't convert `transform`, `NULL`, to a function.hs.

Here is the dput(head()) of my data since the dataset is quite long:

structure(list(Wavenumber = c(648.5568, 652.2841, 656.0115, 659.7388, 
663.4661, 667.1935), X2024.05.17T12.35.56 = c(0.013939, 0.013429, 
0.011292, 0.008814, 0.009864, 0.006855), Wavelength = c(0.00154188499758232, 
0.00153307431531751, 0.00152436352106632, 0.00151575138524519, 
0.0015072360140179, 0.00149881556100292)), row.names = c(NA, 
6L), class = "data.frame")

Solution

  • The easiest way to create the secondary axis is to directly use the transformation formula in the secondary axis definition.

    ggplot(new_df_test, aes(x = Wavenumber, 
                            y = X2024.05.17T12.35.56)) + 
      geom_line() + 
      scale_x_continuous(sec.axis = sec_axis(transform = ~1/.x))
    

    image with sec axis