如果我理解正确,那么实现您想要的结果的一种方法是添加一些虚假的图例条目,我们通过移除标签并将填充颜色设置为例如,使图例键“不可见”。
"transparent"
。
作为第一步,这需要转换
param
并在正确的位置添加伪元素。此外,我们必须设置
drop=FALSE
以使未使用的伪元素实际显示在图例中。最后,只加粗一些图例元素是最简单的任务,可以通过
ggtext::element_markdown
。
注意:根据
theme
将填充颜色设置为
“透明”
不足以使伪元素不可见,例如在默认情况下
theme_grey
按键的背景填充为灰色。因此,我补充道
legend.key = element_rect(fill = "transparent")
以使背景填充也透明。
library(ggplot2)
library(scales)
library(dplyr)
DF$param <- factor(DF$param, c("a", "b", "spacer", "c", "d", "e"))
pal_fill <- scales::hue_pal()(5)
names(pal_fill) <- letters[1:5]
pal_fill <- c(pal_fill, spacer = "transparent")
ggplot(data = DF) +
geom_col(aes(y = val, fill = param, x = x),
position = position_dodge2(preserve = "single")
) +
scale_fill_manual(
values = pal_fill,
drop = FALSE,
labels = ~ dplyr::case_match(
.x, "spacer" ~ "", c("a", "b") ~ paste0("**", .x, "**"),
.default = .x)
) +
guides(fill = guide_legend(
nrow = 2, byrow = TRUE
)) +
theme(
legend.text = ggtext::element_markdown(),
legend.key = element_rect(fill = "transparent")
)
编辑
不得不承认,我不知道到底是什么问题,但解决办法是
alpha
对于我使用的“垫片”为零
after_scale
和
if_else
在里面
geom_col
:
ggplot(data = DF) +
geom_col(
aes(
y = val, fill = param, x = x,
alpha = after_scale(if_else(fill != "transparent", .6, 0))
),
position = position_dodge2(preserve = "single")
) +
scale_fill_manual(
values = pal_fill,
drop = FALSE,
labels = ~ dplyr::case_match(
.x, "spacer" ~ "", c("a", "b") ~ paste0("**", .x, "**"),
.default = .x
)
) +
guides(fill = guide_legend(
nrow = 2, byrow = TRUE
)) +
theme(
legend.position = c(.9, .75),
legend.background = element_rect(fill = alpha("#e5e5e5", 0.60)),
#legend.text = ggtext::element_markdown(),
legend.key = element_rect(fill = "transparent")
)