使用贴标机通过ggplot2和facet_wrap向条带标签添加单位

lvmkulzt  于 2023-02-01  发布在  其他
关注(0)|答案(3)|浏览(125)

我正在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)
ws51t4hk

ws51t4hk1#

labeller中使用lambda或匿名函数可以执行以下操作:

library(ggplot2)

ggplot(df) +
  geom_boxplot(aes(y = output))+
  facet_wrap(vars(group), labeller = labeller(group = ~ paste(.x, "mg")))

rjee0c15

rjee0c152#

我认为您通常会在创建图之前修改数据框。这可能不是您正在寻找的,但我认为这是最实用的解决方案

df2 <- 
  df %>%
  mutate(
    group2 = paste(group, "mg")
  )

ggplot(df2) +
  geom_boxplot(aes(y = output)) +
  facet_wrap(vars(group2))
hrysbysz

hrysbysz3#

您可以创建自己的贴标机功能,如下所述:https://ggplot2.tidyverse.org/reference/labeller.html
例如,

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- tibble(
  group = factor(rep(1:3, times = 5)),
  output = sample(1:10, 15, replace = TRUE)
)

unit_labeller <- function(string) {
  labeled_string <- paste(string, "mg")
  return(labeled_string)
}

df %>%
  ggplot()+
  geom_boxplot(aes(y = output))+
  facet_wrap(vars(group), labeller = labeller(group = unit_labeller))

reprex package(v2.0.1)于2023年1月31日创建

相关问题