如何使用ggplot2在双因素面的特定图上添加不同的垂直线?

时间:2016-03-10 09:22:05

标签: r ggplot2

这是我使用mtcars绘图的代码。

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

我的问题是如何为切面中的不同图形添加不同的垂直线?例如,将xintercept = c(10,20)放在左边的两个图上,并将xintercept = c(15,25,35)放在右边两个图上。

从之前的帖子中,我只能找到如何为单因素方面做到这一点。

非常感谢。

2 个答案:

答案 0 :(得分:2)

我发现最简单的方法是在单独的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

答案 1 :(得分:2)

答案在帮助文件?geom_hline()

中给出

那里的例子是:

# 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)

因此,对于您的示例,这可能是:

# 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