我有2个要绘制在一起的数据集。如果第二个数据集中的数据符合特定条件,则应使用半透明的红色绘制该图,否则不可见。
此外,我想为第二个图添加一个子图例,但仅包含1个元素(红色和标签= FALSE)
在下面的示例中,只有变量“ id_1”中的第一个条与该条件匹配,因此具有覆盖的红色条。但是我仍然缺少正确的图例。
测试数据:
df <- structure(list(id = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("id_1", "id_2"), class = "factor"),
day = structure(c(17897, 17903, 17910, 17917, 17897, 17903,
17910, 17917, 17897, 17903, 17910, 17917, 17897, 17903, 17910,
17917, 17897, 17903, 17910, 17917, 17897, 17903, 17910, 17917,
17897, 17903, 17910, 17917, 17897, 17903, 17910, 17917), class = "Date"),
variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("reas_1", "reas_12",
"reas_123", "reas_1234"), class = "factor"), value = c(0,
0, 3, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 2, 1, 0, 1, 0, 0, 5,
0, 0, 0, 2, 0, 1, 6, 10, 0, 1, 9, 6)), row.names = c(NA,
-32L), class = "data.frame")
overlay <- structure(list(id = structure(1:2, .Label = c("id_1", "id_2"), class = "factor"),
day = structure(c(17897, 17897), class = "Date"), variable = structure(c(1L,
1L), .Label = "plausible_sum", class = "factor"), value = c(10,
0), fill = c("red", "transparent")), row.names = c(NA, -2L
), class = "data.frame")
cbPalette <- c('#3652a3', '#60a0df', '#b7dbff', '#dd0000', '#fd7676')
legendLabels <- c("Var1", "Var2", "Var3", "Var4")
地块代码:
library(ggplot2)
ggplot() +
geom_bar(data = df, aes(x = day, y = value, fill = variable), stat = "identity", width = 3) +
geom_bar(data = overlay, aes(x = day, y = 16), fill = overlay$fill,
alpha = c(0.3, 0), stat="identity", width = 3) +
facet_wrap(~id, nrow = 1) +
scale_fill_manual(name = "Vars: ", values = c(cbPalette), labels = c(legendLabels))
结果与预期:
答案 0 :(得分:1)
在aes()
部分的geom_bar(data=overlay,...)
中分配一个值。这样,您就可以在scale_*_manual()
函数中对此元素的图例框进行操作。在此示例中,我分配了aes(..., colour="FALSE")
,并使用scale_colour_manual()
参数在guide
中编辑了图例。 override.aes()
可让您操纵图例的美学参数。
library(ggplot2)
ggplot() +
geom_bar(data = df, aes(x = day, y = value, fill = variable), stat = "identity", width = 3) +
geom_bar(data = overlay, aes(x = day, y = 16, colour="FALSE"), fill = overlay$fill,
alpha = c(0.3, 0), stat="identity", width = 3) +
facet_wrap(~id, nrow = 1) +
scale_fill_manual(name = "Vars: ", values = c(cbPalette), labels = c(legendLabels)) +
scale_colour_manual(values = c("FALSE" = "transparent"),
name=c("Overlay"),
guide=guide_legend(override.aes = list(fill=overlay$fill[[1]],
alpha=0.3)))
图: