ggplot2设置x和y标记以始终emracass数据

时间:2014-01-24 00:51:27

标签: r ggplot2

我想绘制x vs y。两者都是连续变量。我希望x和y刻度总是绑定数据。换句话说,最小的xtick最多需要min(x),最大的xtick需要至少为max(x)。 y也是如此。

我试过了:

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通常将主要网格附近的抽搐放置)成为边界框,那就更好了。

有什么建议吗?

1 个答案:

答案 0 :(得分: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)