修改组合图的y轴

时间:2014-03-07 06:17:12

标签: r ggplot2

我正在尝试修改ggplot2 wiki中给出的此示例的y轴限制。

library(ggplot2)
x <- seq(1992, 2002, by=2)

d1 <- data.frame(x=x, y=rnorm(length(x)))
xy <- expand.grid(x=x, y=x)
d2 <- data.frame(x=xy$x, y=xy$y, z= jitter(xy$x + xy$y))

d1$panel <- "a"
d2$panel <- "b"
d1$z <- d1$x

d <- rbind(d1, d2)

p <- ggplot(data = d, mapping = aes(x = x, y = y))
p <- p + facet_grid(panel~., scale="free")
p <- p + layer(data= d1,  geom = c( "line"), stat = "identity")
p <- p + layer(data=d2, mapping=aes(colour=z, fill=z),  geom =
c("tile"), stat = "identity")
p

是否可以修改面板“a”的Y轴限制?我想改变ymax = 1.5。

enter image description here

1 个答案:

答案 0 :(得分:1)

尽管有劝告,但可以在不修改数据的情况下完成。

将NA颜色的geom(此处为geom_hline)添加到所需的y值到面板“a”(即,确保geom_hline的数据框设置为d1)。但我认为grid.arrange选项会更整洁。

library(ggplot2)
x <- seq(1992, 2002, by=2)
set.seed(17)
d1 <- data.frame(x=x, y=rnorm(length(x)))
xy <- expand.grid(x=x, y=x)
d2 <- data.frame(x=xy$x, y=xy$y, z= jitter(xy$x + xy$y))
d1$panel <- "a"
d2$panel <- "b"
d1$z <- d1$x
d <- rbind(d1, d2)

p <- ggplot(data = d, mapping = aes(x = x, y = y))
p <- p + facet_grid(panel~., scale="free")
p <- p + layer(data= d1,  geom = c( "line"), position = "identity", stat = "identity") + 
   geom_hline(data = d1, aes(yintercept = 1.5), colour = NA)

p <- p + layer(data=d2, mapping=aes(colour=z, fill=z),  geom =c("tile"), position = "identity", stat = "identity")
p <- p + scale_y_continuous(breaks = c(seq(-1.5, 1.5, .5), seq(1992, 2002, 2))) +
   scale_x_continuous(breaks = seq(1992, 2002, 2))

enter image description here