2014-01-24 22 views
1

我想繪製x vs y。兩者都是連續變量。我希望x和y滴答總是綁定數據。換句話說,最小的xtick需要至多是min(x),最大的xtick需要至少是max(x)。 y也是如此。ggplot2設置x和y刻度以始終emcompass數據

我嘗試這樣做:

seq_ticks <- function(n) {function(limits) pretty(limits, n)} 
p<-ggplot(mpg, aes(x=cty))+theme_bw()+geom_line(aes(y=hwy)) 
p <- p+scale_x_continuous(breaks=seq_ticks(10))+scale_y_continuous(breaks=seq_ticks(10)) 

它將即使最外面的大網格(GGPLOT2通常把靠近主要電網抽動)變爲邊界框更好。

有什麼建議嗎?

+0

聽起來有點關係湯姆的問題在這裏:http://stackoverflow.com/questions/11427212/set-upper-限制在ggplot-to-include-label-greater-the-maximum-value – CMichael

回答

1

兩個選項:

library(ggplot2) 
# evenly spaced, but not so pretty breaks 
breaks.x <- with(mpg,round(seq(min(cty),max(cty),length.out=10),digits=1)) 
breaks.y <- with(mpg,round(seq(min(hwy),max(hwy),length.out=10),digits=1)) 
ggplot(mpg, aes(x=cty, y=hwy))+ 
    geom_line() + 
    theme_bw()+ 
    scale_x_continuous(breaks=breaks.x) + scale_y_continuous(breaks=breaks.y) 

# pretty breaks, with extra grid lines at the limits 
breaks.x <- with(mpg,pretty(seq(min(cty),max(cty),length.out=10))) 
if (min(mpg$cty)>min(breaks.x)) breaks.x[1] <- min(mpg$cty) 
if (max(mpg$cty)<max(breaks.x)) breaks.x[length(breaks.x)] <- max(mpg$cty) 
breaks.y <- with(mpg,pretty(seq(min(hwy),max(hwy),length.out=10))) 
if (min(mpg$hwy)>min(breaks.y)) breaks.y[1] <- min(mpg$hwy) 
if (max(mpg$hwy)<max(breaks.y)) breaks.y[length(breaks.y)] <- max(mpg$hwy) 
ggplot(mpg, aes(x=cty, y=hwy))+ 
    geom_line() + 
    theme_bw()+ 
    scale_x_continuous(breaks=breaks.x) + scale_y_continuous(breaks=breaks.y) 

+1

兩者看起來不錯。我會爲我的需求選擇第二個選項。順便說一句,有人可以告訴我爲什麼使用「漂亮」不起作用,即使「漂亮」包圍範圍。如果ggplot落在數據範圍之外,它會忽略主要的網格嗎? – user3230091