2016-08-04 34 views
6

我想使用ggplot2中的geom_ribbon繪製陰影置信範圍。但是,如果其中一條線超出了設定的限制範圍,則色帶會被切斷而不會延伸到圖的邊緣。ggplot色帶在y極限切斷

小例子

x <- 0:100 
y1 <- 10+x 
y2 <- 50-x 

ggplot() + theme_bw() + 
    scale_x_continuous(name = "x", limits = c(0,100)) + 
    scale_y_continuous(name = "y", limits = c(-20,100)) + 
    geom_ribbon(aes(x=x, ymin=y2-20, ymax=y2+20), alpha=0.2, fill="#009292") +  
    geom_line(aes(x=x , y=y1)) + 
    geom_line(aes(x=x , y=y2)) 

enter image description here

我想是重現相同的行爲,我在基地R,在遮光延伸到邊緣

plot(x, y1, type="l", xlim=c(0,100),ylim=c(-20,100)) 
lines(x,y2) 
polygon(c(x,rev(x)), c(y2-20,rev(y2+20)), col="#00929233", border=NA) 

密謀得到enter image description here

+0

... –

+0

的[限制可能的重複GGPLOT2軸而不刪除數據(外部限制):縮放](http://stackoverflow.com/questions/25685185/limit-ggplot2-axes-without-removing-data-outside-limits-zoom) – aosmith

回答

9

概率lem是limits正在刪除所有不在其範圍內的數據。 你想要的是首先繪製,然後放大。這可以通過使用coord_cartesian來完成。在`scale_y_continuous使用`OOB =尺度:: squish`()`調用是有用的,但創造它自己的一些文物

ggplot() + theme_bw() + 
    geom_ribbon(aes(x=x, ymin=y2-20, ymax=y2+20), alpha=0.2, fill="#009292") +  
    geom_line(aes(x=x , y=y1)) + 
    geom_line(aes(x=x , y=y2)) + 
    coord_cartesian(ylim = c(-25, 100), xlim =c(0,100)) 

enter image description here