plot secondary axis on a different scale in geom line

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

You can use secondary axis via scale_y_continious(sec.axis = dup_axis()). This takes a transformation as an argument. So this is something I would do:

library(tidyverse)

df <- data.frame(
    date = Sys.Date() - 0:9,
    n = rnorm(10, 200, 10), 
    p = 210
  ) %>% 
  mutate_if(is.numeric,round,0) %>% 
  mutate(perc = n/p) 

df
#>          date   n   p      perc
#> 1  2020-06-29 190 210 0.9047619
#> 2  2020-06-28 211 210 1.0047619
#> 3  2020-06-27 182 210 0.8666667
#> 4  2020-06-26 209 210 0.9952381
#> 5  2020-06-25 183 210 0.8714286
#> 6  2020-06-24 218 210 1.0380952
#> 7  2020-06-23 186 210 0.8857143
#> 8  2020-06-22 185 210 0.8809524
#> 9  2020-06-21 200 210 0.9523810
#> 10 2020-06-20 209 210 0.9952381

df %>% 
  mutate(perc = perc * 200) %>% 
  ggplot(aes(x = date, y = n)) + 
    geom_line(aes(y = perc), color = "dodgerblue") +
    geom_line() + 
    scale_y_continuous(
      #limits = c(0, 1),
      sec.axis = dup_axis(~ . / 2, name = "perc")
    ) +
    theme(
      axis.text.y.right = element_text(color = "dodgerblue"),
      axis.title.y.right = element_text(color = "dodgerblue")
    )

Created on 2020-06-29 by the reprex package (v0.3.0)

EDIT: Maybe some words on the chart itself. There is a reason why Hadley Wickham did not want to have secondary axes in ggplot2 and it is also not very appreciated in the dataviz community in general. As one can see here it can be very hard to interpret. You may want to switch to a 2-plot-solution anyway.

2 Likes

Hello. Thank you for the solution. I totally agree that secondary axes aren't a good way to visualize data, however sometimes the client just want it. They simply don't care, no matter the discourse about effective plotting. Unfortunately we have to do it anyway :wink:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.