0

I am trying to plot a line chart with 2 lines but with different scales: the left y axis as a continuous numeric and the right y axis as a percentage. Bellow is a sample:

data.frame(date=Sys.Date()-0:9,n=rnorm(10,200,10),p=210) %>%
  mutate_if(is.numeric,round,0) %>% 
  mutate(perc=n/p) %>% 
  ggplot(.,aes(x=date)) + 
    geom_line(aes(y=n)) + 
    geom_line(aes(y=perc))

How can I accomplish that ?

Thanks

denis
  • 5,580
  • 1
  • 13
  • 40
  • 1
    Repeat of https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales. Basically ggplot purposefully does not support dual axes, but there are workarounds. – John Harley Jun 29 '20 at 21:58
  • Does this answer your question? [ggplot with 2 y axes on each side and different scales](https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales) – denis Jun 30 '20 at 06:35

1 Answers1

0

You can use scale_y_continuous to define a second axis. I changed a bit your example as you two variable were identical if the axis were scaled similarly.

data.frame(date=Sys.Date()-0:9,n=rnorm(10,200,10),p=rnorm(10,200,10)) %>%
  mutate_if(is.numeric,round,0) %>% 
  mutate(perc=n/p) %>% 
  ggplot(.,aes(x=date)) + 
  geom_line(aes(y=n)) + 
  geom_line(aes(y=perc*200))+
  scale_y_continuous(
    sec.axis = sec_axis(~./210,name = "percent")
  )
denis
  • 5,580
  • 1
  • 13
  • 40