问题描述
我正在尝试按组绘制折线图,我想在此添加底纹底纹,覆盖类别的 min
和 max
值.我想复制这样的图,但是灰色阴影覆盖了虚线和实心黑线之间的所有内容(未显示置信区间):
I am trying to plot a line plot by groups, where I would like to add underling shading covering min
and max
values for categories. I would like to replicate plot like this, but grey shade covers all between the dashed and solid black lines (not showing confidence interval):
通常,这是使用 geom_ribbon
完成的,我需要为 aes(ymin = ymin,ymax = ymax)
指定值.但是如何为组 c
和 a
的值传递 ymin
和 ymax
值(在我的示例中)?
Normally, this is done using geom_ribbon
where I need to specify values for aes(ymin = ymin, ymax = ymax)
. But how to pass the ymin
and ymax
values for values of group c
and a
(in my example)?
这是我的虚拟示例:
# example for shaded line plot
dd <- data.frame(year = c(1:5),
group = rep(c("a", "b", "c"), each = 5),
vals = c(5, 5.2, 5.6, 5.8, 6,
5, 4.9, 4.8, 4.7, 4.2,
5, 4.8, 4.4, 4, 3))
dd %>%
ggplot(aes(x = year,
y = vals,
shape = group,
color = group,
linetype = group)) +
ylim(0,6.5) +
geom_line(lwd = 1.5) +
theme_bw()
我的数据格式很长,并且我有很多组,所以我希望能使用一些自动解决方案.预先谢谢你.
My data are in long format and I have many groups, so I would appreciate some automatic solution. Thank you in advance.
我的方法:
将数据从长格式转换为宽格式,以argumens作为 ymin
和 ymax
传递.无法使用两个不同的数据框:
convert data from long to wide format to pass argumens as ymin
and ymax
. Not working as using two different dataframes:
# maybe first convert data from long to wide?
library(tidyr)
dd.spread <- spread(dd, group, vals)
dd %>%
ggplot(aes(x = year,
y = vals,
shape = group,
color = group,
linetype = group)) +
geom_line() +
geom_ribbon(dd.spread, aes(ymin = c, ymax = a), color = "grey70")
预期结果(在a-c之间阴影)
Expected outcome (shaded between a-c):
推荐答案
您可以在层的 data
参数中放置一个偷偷摸摸的 pivot_wider
.在下面的示例中,我将一些美感从主绘图调用迁移到了线层,因为它们在功能区中相互冲突.
You can put in a sneaky pivot_wider
at the data
argument of a layer. In the example below I migrated some aesthetics from the main plot call to the line layer, as they were conflicting in the ribbon layer.
library(ggplot2)
library(tidyr)
#> Warning: package 'tidyr' was built under R version 4.0.3
# example for shaded line plot
dd <- data.frame(year = c(1:5),
group = rep(c("a", "b", "c"), each = 5),
vals = c(5, 5.2, 5.6, 5.8, 6,
5, 4.9, 4.8, 4.7, 4.2,
5, 4.8, 4.4, 4, 3))
dd %>%
ggplot(aes(x = year)) +
ylim(0,6.5) +
geom_ribbon(
data = ~ pivot_wider(., names_from = group, values_from = vals),
aes(ymin = c, ymax = a)
) +
geom_line(aes(y = vals,
color = group,
linetype = group),
lwd = 1.5) +
theme_bw()
这篇关于使用组摘要值作为ggplot2中的geom_ribbon?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!