ggplot with facets和geom_abline

时间:2018-01-15 22:01:46

标签: r ggplot2 facet

假设我有这样的数据:

n <- 100
set.seed(123)    
df <- data.frame(
    num1 = rnorm(n),
    num2 = sample(1:4, n, replace = TRUE),
    char = sample(c("Green", "Red", "Blue"), n, replace = TRUE),
    fac  = factor(sample(c("Green", "Red", "Blue"), n, replace = TRUE)),
    logical = sample(c(TRUE, FALSE), n, replace = TRUE),
    stringsAsFactors = FALSE
)

我想生成一个带有facets和参考线的ggplot ,以便在相应的facet中绘制参考线。例如:

## Base plot
ggplot(df, aes(num2, num1)) + 
geom_jitter() + 
facet_grid(~ char)

enter image description here

现在我想在logical == TRUE时添加垂直线条。

enter image description here

类似的东西:

## Does not work
ggplot(df, aes(num2, num1)) + 
geom_jitter() + 
facet_grid(~ char) +
geom_vline(xintercept = num2)

1 个答案:

答案 0 :(得分:2)

您需要在aes()内映射xintercept值,告诉ggplot查看data内部的内容。并根据您的条件对该层的数据进行子集化。

ggplot(df, aes(num2, num1)) + 
    geom_jitter() + 
    facet_grid(~ char) +
    geom_vline(data = df[df$logical == TRUE,], aes(xintercept = num2))

enter image description here