Search code examples
rggplot2plotoverlayaxes

Overlay two ggplots with different x and y axes scales


Let's suppose I have two data.frames as follows:

df_1=data.frame(x=c(1:200), y=rnorm(200))

df_2=rpois(100000, 1)
df_2=data.frame(table(df_2))
df_2$df_2=as.numeric(levels(df_2$df_2))[df_2$df_2]

When I plot them singularly I get:

library(ggplot2)
p1=ggplot() +
  geom_line(data=df_1, aes(x=x,y=y))

print(p1)

enter image description here

p2=ggplot() +
  geom_line(data=df_2, aes(x=df_2,y=Freq))

print(p2)

enter image description here

These two plots have different x and y axes.

How can I overlay the two plots into one?

Thanks


Solution

  • Here is another option. We can use the sec.axis argument in the scale_*_continuous() function to map the data on top of each other through transformations.

    ggplot() +
      geom_line(data=df_1, aes(x=x,y=y))+
      geom_line(data=df_2, aes(x=df_2*25,y=Freq/9000))+
      scale_x_continuous(sec.axis = sec_axis(trans = ~./25))+
      scale_y_continuous(sec.axis = sec_axis(trans = ~.*9000))
    

    The rescaling is arbitrary, so you can play with it until it looks good to you.