Jd Baba
Jd Baba

Reputation: 6118

Modifying y axis for combined plots

I am trying to modify the y axis limit for this example given in ggplot2 wiki.

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

Is it possible to modify Y axis limits for panel "a" ? I want to change ymax = 1.5.

enter image description here

Upvotes: 1

Views: 123

Answers (1)

Sandy Muspratt
Sandy Muspratt

Reputation: 32789

Admonishments notwithstanding, it can be done without modifying the data.

Add a NA coloured geom (here, geom_hline) at the desired y value to panel "a" (that is, make sure the data frame is set to d1 for geom_hline). But I think the grid.arrange option would be neater.

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

Upvotes: 1

Related Questions