0

I am trying to plot a line (month over month pct change) as a secondary axis, however it just shows as a horizontal line at the bottom of the chart. Here is the code to generate the data -

library(tidyverse)

dates <- as.Date(c( "2020-08-01", "2020-09-01", "2020-10-01", "2020-11-01", "2020-12-01", "2021-01-01",
            "2021-02-01", "2021-03-01", "2021-04-01", "2021-05-01", "2021-06-01", "2021-07-01"))

values <- runif(12, 700, 1500)

df <- tibble(dates, values) %>% 
    arrange(dates) %>% 
    mutate(lag_1 = lag(values, 1),
           diff = values - lag_1,
           pct = diff/values)

ggplot(df)+
    geom_col(aes(dates, values), fill = "grey")+
    geom_line(aes(dates, pct))+
    scale_y_continuous(sec.axis = sec_axis(~./1500))

When I run the last bit of code (to plot) I get the this result enter image description here

How can I plot the pct column as a secondary axis? I'm not really sure how the sec.axis inputs should be specified.


The Rookie
  • 683
  • 6
  • 9
  • I think it is better to have it in two plots as secondary axis plots are not really recommended. i.e. `library(patchwork); p1 – akrun Aug 22 '21 at 19:41

0 Answers0