使用标签函数重命名ggplot2

问题描述 投票:0回答:1

当在GGPLOT2中使用Labeller函数时,只有在查找表中找到原始值时才能应用它?在下面的示例中,我正在使用

as_labeller()
重命名一些汽车类。查找表中没有的任何内容都默认为“ na”。我希望它保留其原始名称。这可能吗?

library(ggplot2)

#base plot without any labels
p <- ggplot(mpg, aes(displ, hwy)) + geom_point()
p + facet_wrap(~class)

#add fancy labels - but only for some classes
fancy_labs <- as_labeller(c('2seater' = 'Seats Two!', 'compact' = "Small Family Car"))
p + facet_wrap(~class, labeller = fancy_labs)

enter image description here enter image description here

我想要第二个情节的标题来读:“座位两个!” “小型家庭汽车”“中型”“小型货车”(等)

r ggplot2 label facet-wrap
1个回答
0
投票

据我所知,如果事物与

as_labeller
不匹配,我看不到易于指定默认值,但是您也可以将功能作为标记器包装,并且可以使用
dplyr::case_match
作为助手。例如

fancy_labs <- as_labeller(\(x) dplyr::case_match(x, 
  '2seater' ~ 'Seats Two!',
  'compact' ~ "Small Family Car",
  .default=x)
)
p + facet_wrap(~class, labeller = fancy_labs)

enter image description here

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.