2

I want to draw two different geom_ablines in my two facets. Which seem to be working differently to the geom_hline - which is answered here.

While

library(ggplot2)
dummy1 <- expand.grid(X = factor(c("A", "B")), Y = rnorm(10))
dummy1$D <- rnorm(nrow(dummy1))
dummy2 <- data.frame(X = c("A", "B"), Z = c(1, 0))
ggplot(dummy1, aes(x = D, y = Y)) + geom_point() + facet_grid(~X) + 
    geom_hline(data = dummy2, aes(yintercept = Z))

.. works, this:

library(ggplot2)
dummy1 <- expand.grid(X = factor(c("A", "B")), Y = rnorm(10))
dummy1$D <- rnorm(nrow(dummy1))
dummy2 <- data.frame(X = c("A", "B"), Z = c(1, 0))
ggplot(dummy1, aes(x = D, y = Y)) + geom_point() + facet_grid(~X) + 
   geom_abline(data = dummy2, aes(yintercept = Z), slope = 1)

does not:

abline using facets

Y-intercept is not affected.

Community
  • 1
  • 1
Boern
  • 7,233
  • 5
  • 55
  • 86

1 Answers1

6

For geom_abline you need intercept and not yintercept. Furthermore, you need to map both values inside aes, otherwise setting slope overrides what you set with aes. This works:

library(ggplot2)
dummy1 <- expand.grid(X = factor(c("A", "B")), Y = rnorm(10))
dummy1$D <- rnorm(nrow(dummy1))
dummy2 <- data.frame(X = c("A", "B"), Z = c(1, 0))

ggplot(dummy1, aes(x = D, y = Y)) +
  geom_point() +
  facet_grid(~X) + 
  geom_abline(data = dummy2, aes(intercept = Z, slope = 1))
Thomas K
  • 3,242
  • 15
  • 29