Intro Thoughts

Status Quo

library(tidyverse)
gapminder::gapminder |>
  filter(country == "Belgium") ->
belgium

belgium |>
  ggplot() + 
  aes(x = year, y = lifeExp) + 
  geom_line() + 
  geom_line(aes(y = I((gdpPercap- min(gdpPercap))/
                        (max(gdpPercap)-min(gdpPercap)))))

compute_group_y2 <- function(data, scales, min_pos = .05, max_pos = .95){
  
  data |> 
    mutate(y = (max_pos - min_pos) * (I((y2- min(y2))/
                        (max(y2)-min(y2)))) + min_pos) 
  
}  

compute_group_y2_text <- function(data, scales, min_pos = .05, max_pos = .95){

  data |> 
  reframe(label = round(c(min(y2), max(y2)))) |>
    mutate(y = I(c(min_pos, max_pos)),
           x = I(.975),
           hjust = 0)


}

library(statexpress)
belgium |>
  ggplot() + 
  aes(x = year, y = lifeExp, y2 = gdpPercap/1000) + 
  geom_col() + 
  geom_line(stat = qstat(compute_group_y2),
            aes(color = "second axis")) + 
  geom_text(stat = qstat(compute_group_y2_text),
            aes(color = "second axis"))
## Warning: The following aesthetics were dropped during statistical transformation: y2.
## ℹ This can happen when ggplot fails to infer the correct grouping structure in
##   the data.
## ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
##   variable into a factor?

compute_group_y2 <- function(df, min_pos = 0, max_pos = 1){
  
  df |> 
    mutate(y = (max_pos - min_pos) *I((y2- min(y2))/
                        (max(y2)-min(y2))) + min_pos) 
  
}  

belgium |>
  ggplot() + 
  aes(x = year, 
      y = lifeExp, 
      y2 = gdpPercap) + 
  geom_line() + 
  geom_line(stat = "manual",
            fun = compute_group_y2,
            aes(color = "second axis"),
            args = c(min_pos = .5, max_pos = .9)) 

last_plot() +
  scale_y_continuous(sec.axis = sec_axis(~ . + 10))

Experiment

Closing remarks, Other Relevant Work, Caveats