Search code examples
rplotggplot2scale

scale_y_continuous removes one graph from the plot


Very simple question for the ggplot2 gurus out there I'm sure.

Here is my code with the plot output each time

x <- data.frame(date = seq(as.Date("2012-01-01"),as.Date("2012-12-31"),
 by="week"), rain = sample(0:20,53,replace=T),
 flow = sample(50:200,53,replace=T))

var1 <- "rain"
var2 <- "flow"
xVariable <- "date"

fnxVariable <- function(x){return(xVariable)}
fnvar1 <- function(x){return(var1)}
fnvar2 <- function(x){return(var2)}

x$var1scaled <- x[,var1] * (max(x[,var2])-min(x[,var2]))/max(x[,var1])
+ (min(x[,var2])-min(x[,var1],na.rm=T))  

tickNumber <- 5
ylimits <- seq(floor(min(x[,var1])),ceiling(max(x[,var1])), 
by = (ceiling(max(x[,var1])) - floor(min(x[,var1])))/tickNumber)
ylimits2 <- floor(ylimits * max(x[,var2])/max(x[,var1]) + 
(min(x[,var2])-min(x[,var1],na.rm=T)))

g.bottom <- ggplot(x, aes_string(x = fnxVariable(""), y = fnvar2("")))
g.bottom <- g.bottom+geom_line()
g.bottom

enter image description here

g.bottom <- g.bottom+geom_bar(aes_string(y = "var1scaled"),stat="identity")
g.bottom

enter image description here

g.bottom <- g.bottom + scale_y_continuous(expand = c(0,0), 
limits = c(min(x[,var2]),max(x[,var2]))) 
g.bottom

enter image description here

Any idea why this is happenning ? I tried reading through the ggplot2 help on expand but couldn't figure it out.

PS : This is an extract of a function hence the aes_string convoluted use.


Solution

  • If you use the limits= inside the scale_y_continuous() then all the data that are outside the limits are removed. Your bars starts at 0 point and therefore are removed because minimal y value is set higher.

    You should remove limits= from scale_y_continous() and use coord_cartesian() with ylim= instead. This will "zoom" your plot without removing data.

    g.bottom + scale_y_continuous(expand = c(0,0))+
          coord_cartesian(ylim=c(min(x[,var2]),max(x[,var2])))
    

    enter image description here