didimichael
didimichael

Reputation: 13

How to add different vertical lines on specific plots of the two-factor facets using ggplot2?

This is my code for graphing using mtcars.

p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_wrap(vs ~ am)

My question is how to add different vertical lines for different plots in the facets? For example, putting xintercept=c(10,20) on the left two plots and putting xintercept=c(15, 25,35) on the right two plots.

From the previous posts, I can only find how to do it for one-factor facet.

Thank you very much.

Upvotes: 1

Views: 3601

Answers (2)

erc
erc

Reputation: 10133

The answer is given in the help file ?geom_hline()

The example there is:

# To show different lines in different facets, use aesthetics
p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_wrap(~ cyl)

mean_wt <- data.frame(cyl = c(4, 6, 8), wt = c(2.28, 3.11, 4.00))
p + geom_hline(aes(yintercept = wt), mean_wt)

So for your example this could be:

# create new dataframe
intercept <- data.frame(vs=c(rep(0, 2), rep(1, 2), rep(0,3), rep(1,3)), 
                        am = c(rep(0, 4), rep(1, 6)), 
                        int = c(10, 20, 10, 20, 15, 25, 35, 15, 25, 35))
# add vline to plot
p + geom_vline(aes(xintercept=int), intercept)

enter image description here

Upvotes: 3

David Heckmann
David Heckmann

Reputation: 2939

The easiest way I found was defining your lines in a separate data.frame:

line.df <- data.frame( am = rep(levels(as.factor(mtcars$am)),3) ,am.int = c(10,15,20,25,NA,35) )
line.df <- line.df[!is.na(line.df$am.int),]

library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_wrap(vs ~ am)
p + geom_vline(aes(xintercept = am.int), data = line.df)

enter image description here

Upvotes: 3

Related Questions