我正在ggplot 2中绘制分面图。我分面的组的名称在逻辑上应该包含单位,我希望自动将这些单位添加到条带标签中,而无需手动写出包含所有标签的新向量-即用“1 mg”、“2 mg”、“3”替换标签。“3 mg”。我可以使用类似于下面的简化示例的代码来完成此操作。但单独定义标签向量仍然有点笨拙,我想知道是否有人知道在标签函数本身中完成此操作的方法?这似乎是一个相当常见的场景,所以我很惊讶没有找到更多的例子,其他人是如何做到这一点在线。
df <- tibble(
group = factor(rep(1:3, times = 5)),
output = sample(1:10, 15, replace = TRUE)
)
labs <- paste(levels(df$group), "mg")
names(labs) <- levels(df$group)
df %>%
ggplot()+
geom_boxplot(aes(y = output))+
facet_wrap(vars(group), labeller = labeller(group = labs)
3条答案
按热度按时间ws51t4hk1#
在
labeller
中使用lambda或匿名函数可以执行以下操作:rjee0c152#
我认为您通常会在创建图之前修改数据框。这可能不是您正在寻找的,但我认为这是最实用的解决方案
hrysbysz3#
您可以创建自己的贴标机功能,如下所述:https://ggplot2.tidyverse.org/reference/labeller.html
例如,
由reprex package(v2.0.1)于2023年1月31日创建