1

Suppose I have the following datasets:

The first one is monthly data:

library (ggplot2)
val <- runif(48, -5,5)    
dt <- seq(as.Date("2010/1/1"), by = "month", length.out = 48)     
dat <- data.frame(cbind(val, as.Date(dt)))    
ggplot(dat, aes(dt, val,fill=val)) + geom_bar(stat = 'identity')

The second is annual data with different y scale:

val2 <- runif(4,50,70)
dt2 <- seq(2010,2014) 
dat2 <- data.frame(cbind(val2, dt2))

Is it possible to overlay the 2nd dataset on this plot, having two y axis but one x axis?

enter image description here

Geo-sp
  • 1,704
  • 3
  • 19
  • 42

1 Answers1

2

You can do it, even with two separate data frames, but the result is likely to be misleading and difficult to interpret.

library(tidyverse)
library(lubridate)

set.seed(2)
val <- runif(48, -5,5)    
dt <- seq(as.Date("2010/1/1"), by = "month", length.out = 48)     
dat <- data.frame(val, dt=as.Date(dt))

val2 <- runif(5,50,70)
dt2 <- seq(2010,2014) 
dat2 <- data.frame(val2, dt2)

ggplot() + 
  geom_bar(data=dat, aes(dt, val,fill=val), stat = 'identity') +
  geom_line(data=dat2 %>% mutate(dt2 = ymd(paste0(dt2,"06-30"))),
            aes(dt2, val2/10), colour="red") +
  scale_y_continuous(sec.axis=sec_axis(~.*10, name="val2")) +
  theme(axis.text.y.right=element_text(colour="red"),
        axis.title.y.right=element_text(colour="red"),
        axis.text.y=element_text(colour="#346D9D"),
        axis.title.y=element_text(colour="#346D9D"),
        axis.title.x=element_blank(),
        legend.position="bottom")

enter image description here

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • Maybe one way of dealing with this is plotting the second data in a separate panel and aligning the x axis – Geo-sp Mar 09 '18 at 19:36