最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - Using a labelling function to rename some but not all variables in ggplot2 - Stack Overflow

programmeradmin1浏览0评论

When using a labeller function in ggplot2, is it possible to apply it only when the original value is found in the lookup table? In the example below, I'm using as_labeller() to rename some of the car classes. Anything that isn't in the lookup table defaults to "NA". I'd like it to keep its original name. Is this possible?

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)

I'd like the headers of the second plot to read: "Seats Two!" "Small Family Car" "midsize" "minivan" (etc)

When using a labeller function in ggplot2, is it possible to apply it only when the original value is found in the lookup table? In the example below, I'm using as_labeller() to rename some of the car classes. Anything that isn't in the lookup table defaults to "NA". I'd like it to keep its original name. Is this possible?

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)

I'd like the headers of the second plot to read: "Seats Two!" "Small Family Car" "midsize" "minivan" (etc)

Share Improve this question asked Feb 7 at 21:01 JakenJaken 4652 silver badges8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

As far as I can tell I don't see an easy to specify the default value if things don't match with as_labeller, but you can also wrap a function as a labeller and could use dplyr::case_match as a helper. For example

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)

发布评论

评论列表(0)

  1. 暂无评论