带有 facets 和 geom_abline 的 ggplot
ggplot with facets and geom_abline
假设我有这样的数据:
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
)
我想生成一个带有小平面和参考线的 ggplot ,以便在适当的小平面上绘制参考线。例如:
## Base plot
ggplot(df, aes(num2, num1)) +
geom_jitter() +
facet_grid(~ char)
现在我想在 logical == TRUE
时添加垂直线。
类似于:
## Does not work
ggplot(df, aes(num2, num1)) +
geom_jitter() +
facet_grid(~ char) +
geom_vline(xintercept = num2)
您需要将您的 xintercept 值映射到 aes()
内,以告诉 ggplot 在 data
内查找它。并根据您的条件为该层的数据子集。
ggplot(df, aes(num2, num1)) +
geom_jitter() +
facet_grid(~ char) +
geom_vline(data = df[df$logical == TRUE,], aes(xintercept = num2))
假设我有这样的数据:
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
)
我想生成一个带有小平面和参考线的 ggplot ,以便在适当的小平面上绘制参考线。例如:
## Base plot
ggplot(df, aes(num2, num1)) +
geom_jitter() +
facet_grid(~ char)
现在我想在 logical == TRUE
时添加垂直线。
类似于:
## Does not work
ggplot(df, aes(num2, num1)) +
geom_jitter() +
facet_grid(~ char) +
geom_vline(xintercept = num2)
您需要将您的 xintercept 值映射到 aes()
内,以告诉 ggplot 在 data
内查找它。并根据您的条件为该层的数据子集。
ggplot(df, aes(num2, num1)) +
geom_jitter() +
facet_grid(~ char) +
geom_vline(data = df[df$logical == TRUE,], aes(xintercept = num2))