Search code examples
rggplot2axis-labelsaxesscatter

ggplot: change left and right axis ranges


I need to plot two scatter plots using ggplot. One in which all of the values are positive ranging between (0,0.02) and another in which all of the values are negative ranging between (0,-1500). I have tried to use sec_axis to convey the differing scales but I have been able to produce the following.

enter image description here

This was produced using

library(tidyverse)
library(ggplot2)
scl = with(use_deciles, max(abs(coef_navy))/max(abs(coef_maroon)))

ggplot(use_deciles) + 
  geom_point(aes(x = decile_navy, y = coef_navy, color = 'navy')) + 
  geom_point(aes(x = decile_maroon, y = coef_maroon*scl, color = 'maroon')) +    
  labs(x = "Group", y = "") +
  scale_color_manual(values = c('maroon', 'navy')) + 
  scale_y_continuous(sec.axis = sec_axis(~. /scl, name = "2nd axis"))

As you can see the scl provides the optimal re-scaling between the right and left axis but here is my question:

How can I adjust the ranges of the y axes so that I can put 0 at the top of the left axis but at the bottom of the right axis?

Given that I can only define sec_axis as a linear transformation of the left-axis, I'm not sure if this option can actually shift the labels. If I need to manually re-label the y-axis, that could be ok but I want to first understand how to overlay my scatter plots here.

Thank you in advance.


Solution

  • Try something like this with @jared_mamrot data:

    ggplot(use_deciles) + 
      geom_point(aes(x = count, y = coef_navy, color = 'navy')) + 
      geom_point(aes(x = count, y = coef_maroon*scl-1200, color = 'maroon')) +    
      labs(x = "Group", y = "") +
      scale_color_manual(values = c('maroon', 'navy')) + 
      scale_y_continuous(sec.axis = sec_axis(~(.+1200)/scl, name = "2nd axis"))
    

    You will get this: enter image description here