Search code examples
rggplot2graph

Dual axis graph, keep original scale


I am trying to do a graph plot with two y-scales. I can't just superimpose both plots since they are widely different scale. Ideally, i would like to set the limits of the right hand y-axis so that both plots are superimposed.

Here is my sample data:

df <- data.frame(year= c(2000, 2001, 2002, 2003, 2004, 2005),
                 price= c(100, 105, 102, 110, 98, 102),
                 production= c(10000, 10500, 10250, 10300, 10450, 10320))

And here is my ggplot so far

ggplot() + 
  geom_bar(data= df, aes(x=year, y=production), stat = "identity") +
  geom_line(data= df, aes(x=year, y=price), color= "red") +
  labs(x="Year", y = "Production (Kg)") +
  scale_y_continuous(limits=c(95, 110), 
    sec.axis = sec_axis(~ . *1 , name = "Price ($)")) +
  theme_bw()

Solution

  • To use two axes in ggplot, you have to scale the data in one direction and do the opposite scaling on the axis. The following code makes a primary axis running from 0 to 12000 and a second axis going from 98 to 110, 1/1000 of the primary axis range. Using geom_bar forces the primary axis to start at zero. If you used another geom for that axis, you could scale the primary axis to show the variation in production more clearly. The code will not run in a reprex, but it runs on my system with no error.

    library(ggplot2)
    df <- data.frame(year= c(2000, 2001, 2002, 2003, 2004, 2005),
                     price= c(100, 105, 102, 110, 98, 102),
                     production= c(10000, 10500, 10250, 10300, 10450, 10320))
    ggplot() + 
      geom_bar(data= df, aes(x=year, y=production), stat = "identity") +
      geom_line(data= df, aes(x=year, y=(price-98)*1000), color= "red", linewidth = 1) +
      labs(x="Year", y = "Production (Kg)") +
      scale_y_continuous(limits = c(0,12000), 
                         sec.axis = sec_axis(~ ./1000+98 , name = "Price ($)")) +
      theme_bw() +
      theme(axis.text.y.right = element_text(color = "red"))