25

How do you specify different geoms for different facets in a ggplot?

(Asked on behalf of @pacomet, who wanted to know.)

0

2 Answers 2

51

here is another approach by subsetting data:

ggplot(mtcars, aes(mpg, disp)) + facet_wrap(~cyl) + 
  geom_point(data = subset(mtcars, cyl == 4)) +
  geom_line(data = subset(mtcars, cyl == 6)) +
  geom_text(data = subset(mtcars, cyl == 8), aes(label = gear))

enter image description here

3
  • 6
    you can simplify the code a bit by using subset = .(cyl == 4) instead of using the data call.
    – Ramnath
    Oct 26, 2011 at 15:08
  • 1
    function . is from package plyr but I don't think it's working anymore
    – fc9.30
    Aug 14, 2019 at 11:37
  • 1
    An alternative in recent versions of ggplot is to use data = ~subset(.x, cyl == 4) Mar 24, 2021 at 14:15
3

Here's some sample data with 5 groups (g). We want a different geom type in the fifth facet. Notice the trick of creating two different versions of the y variable, one for the first four facets, and one for the fifth.

dfr <- data.frame(
  x = rep.int(1:10, 5),
  y = runif(50),
  g = gl(5, 10)
)
dfr$is.5 <- dfr$g == "5"
dfr$y.5 <- with(dfr, ifelse(is.5, y, NA)) 
dfr$y.not.5 <- with(dfr, ifelse(is.5, NA, y))

If the different geoms can use the same aesthetics (like point and lines), then it isn't a problem.

(p1 <- ggplot(dfr) +
  geom_line(aes(x, y.not.5)) +
  geom_point(aes(x, y.5)) +
  facet_grid(g ~ .)
)

However, a line plot and a bar chart require different facets, so they don't work toegther as expected.

(p2 <- ggplot(dfr) +
  geom_line(aes(x, y.not.5)) +
  geom_bar(aes(y.5)) +
  facet_grid(g ~ .)
)

In this case it is better to draw two separate graphs, and perhaps combine them with Viewport.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.