R语言 更改多个geom_text标签

b1uwtaje  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(194)

我正在尝试更改geom_text中所有标签的名称,如下例所示:

mpg %>% 
  distinct(trans, .keep_all = T) %>% 
  ggplot(aes(x=cty, y=hwy))+
  geom_text(aes(x=cty, y=hwy,label = trans))

我想根据下面代码中的名称将"auto(l3)"编辑为"Al3",将"auto(l4)"编辑为"Al4",将"auto(l5)"编辑为"Al5",将"auto(l6)"编辑为"Al6",依此类推

mpg %>% 
  distinct(trans, .keep_all = T) %>% 
  ggplot(aes(x=cty, y=hwy))+
  geom_text(aes(x=cty, y=hwy,
                label = replace(trans, c("auto(l3)", "auto(l4)", "auto(l5)", "auto(l6)",
                                         "auto(s4)", "auto(s5)", "auto(s6)",
                                         "manual(m5)", "manual(m6)", "auto(av)"),
                                c("Al3", "Al4", "Al5", "Al6",
                                  "As4", "selected", "good",
                                  "m5", "m6", "av"))))

我的输出是以下错误"Error in check_aesthetics():!美观必须为长度1或与数据相同(10):标签"
我在代码中输入了10个反式值,是否有其他方法可以进行此更改?

uxhixvfz

uxhixvfz1#

我建议在ggplot之外进行这种重新编码。恕我直言,这会使代码更干净,更容易检查和调试。此外,我使用一个命名向量切换到dplyr::recode

library(ggplot2)
library(dplyr)

rec_vec <- setNames(
  c("Al3", "Al4", "Al5", "Al6", "As4", "selected", "good", "m5", "m6", "av"),
  c(
    "auto(l3)", "auto(l4)", "auto(l5)", "auto(l6)", "auto(s4)", "auto(s5)",
    "auto(s6)", "manual(m5)", "manual(m6)", "auto(av)"
  )
)

mpg %>%
  distinct(trans, .keep_all = T) %>%
  mutate(trans = recode(trans, !!!rec_vec)) |>
  ggplot(aes(x = cty, y = hwy)) +
  geom_text(aes(
    x = cty, y = hwy,
    label = trans
  ))

相关问题