英文:
Accentuate range of line in plot - only closed interval
问题
I understand your request. Here's the translated portion:
我想突出 ggplot 线图中的一个封闭区域。这是一个示例:
df = data.frame(
x = c(1,2,3,4,5,1,2,3,4,5),
y = c(1,2,1,2,1,3,4,3,4,3),
se = 0.1,
cond = c(F,T,T,F,F,F,F,T,T,F),
g = c('M','M','M','M','M','F','F','F','F','F')
)
ggplot(df, aes(x=x, y=y, alpha = cond, color = g, group = g)) +
geom_errorbar(aes(ymin=y-2*se, ymax=y+2*se), width=.01) +
geom_line() +
geom_point() +
scale_alpha_manual(values = c(TRUE = 1, FALSE = .3))
这将产生以下图表:
我只想突出 cond == T 的数据点之间的区域,而不是之后的线元素。
如果我尝试以下操作,突出显示是正确的,但线的不同部分不再正确连接:
ggplot(df, aes(x=x, y=y, alpha = cond, color = g)) +
geom_errorbar(aes(ymin=y-2*se, ymax=y+2*se), width=.01) +
geom_line() +
geom_point() +
scale_alpha_manual(values = c(TRUE = 1, FALSE = .3))
英文:
I would like to accentuate a closed range in a ggplot line plot. Here is an example:
df = data.frame(
x = c(1,2,3,4,5,1,2,3,4,5),
y = c(1,2,1,2,1,3,4,3,4,3),
se = 0.1,
cond = c(F,T,T,F,F,F,F,T,T,F),
g = c('M','M','M','M','M','F','F','F','F','F')
)
ggplot(df, aes(x=x, y=y, alpha = cond, color = g, group = g)) +
geom_errorbar(aes(ymin=y-2*se, ymax=y+2*se), width=.01) +
geom_line() +
geom_point() +
scale_alpha_manual(values = c(`TRUE` = 1, `FALSE` = .3))
This produces the following plot:
I would like only the region between the data points with cond == T to be highlighted, not the line element afterwards.
If I try the following, the highlighting is correct, but the different parts of the lines are not properly connected anymore:
ggplot(df, aes(x=x, y=y, alpha = cond, color = g)) +
geom_errorbar(aes(ymin=y-2*se, ymax=y+2*se), width=.01) +
geom_line() +
geom_point() +
scale_alpha_manual(values = c(`TRUE` = 1, `FALSE` = .3))
答案1
得分: 0
你可以创建一个新变量,只有当cond
的值和后续值都为TRUE
时,它才为TRUE
。我们可以使用dplyr::lead()
来实现这一点。然后,在ggplot::geom_line()
的调用中,不再使用cond
作为alpha参数,而是使用新创建的between_cond
。
df <-
df %>%
mutate(between_cond = cond & lead(cond))
ggplot(df, aes(x=x, y=y, alpha = cond, color = g, group = g)) +
geom_errorbar(aes(ymin=y-2*se, ymax=y+2*se), width=.01) +
geom_line(aes(alpha = between_cond)) +
geom_point() +
scale_alpha_manual(values = c(`TRUE` = 1, `FALSE` = .3))
英文:
You can create a new variable that is TRUE
only when the the value for cond
and following value
are TRUE
. We can use dplyr::lead()
for this. Then instead of using cond
for
the alpha argument we use the newly created between_cond
in the ggplot::geom_line()
call.
df <-
df |>
mutate(between_cond = cond & lead(cond))
ggplot(df, aes(x=x, y=y, alpha = cond, color = g, group = g)) +
geom_errorbar(aes(ymin=y-2*se, ymax=y+2*se), width=.01) +
geom_line(aes(alpha = between_cond)) +
geom_point() +
scale_alpha_manual(values = c(`TRUE` = 1, `FALSE` = .3))
<!-- -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论