scale_y_continuous从图中删除一个图

时间:2015-09-17 04:31:37

标签: r plot ggplot2 scale

ggplot2专家非常简单的问题我确定。

这是我的代码,每次都有情节输出

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

知道为什么会这样吗?我尝试通过ggplot2帮助阅读扩展但无法弄明白。

PS:这是一个函数的摘录,因此aes_string进行了错综复杂的使用。

1 个答案:

答案 0 :(得分:1)

如果您使用limits=内的scale_y_continuous(),则会移除超出限制的所有数据。您的条形从0开始,因此被移除,因为最小y值设置得更高。

您应该从limits=移除scale_y_continous(),然后使用coord_cartesian()代替ylim=。这将在不删除数据的情况下“缩放”您的绘图。

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

enter image description here