【问题标题】:How to control which facet_wrap labels are displayed如何控制显示哪些 facet_wrap 标签
【发布时间】:2021-11-12 13:43:37
【问题描述】:
在facet_wrap 的以下使用中,year 和 model 都显示在绘图标签中。
library(tidyverse)
mpg %>%
filter(manufacturer=='audi')%>%
ggplot(aes(cty, hwy)) +
geom_point(aes(col = model)) +
facet_wrap(year~model)
我们已经用model 为点着色,并显示在图例中,因此我们实际上不需要在每个方面标签中使用model。我们如何从标签中删除model?
【问题讨论】:
标签:
r
ggplot2
facet
facet-wrap
【解决方案1】:
最简单的方法是调整 labeler 函数以仅提取第一个变量的标签。你可以这样做
mpg %>%
filter(manufacturer=='audi')%>%
ggplot(aes(cty, hwy)) +
geom_point(aes(col = model)) +
facet_wrap(~year+model, labeller=function(x) {x[1]})
另一种方法是创建一个交互变量,这样您就只对一个变量进行分面,然后您可以更改标签器以去除第二个值的名称。应该是这样的
mpg %>%
filter(manufacturer=='audi')%>%
ggplot(aes(cty, hwy)) +
geom_point(aes(col = model)) +
facet_wrap(~interaction(year,model), labeller=as_labeller(function(x) gsub("\\..*$", "", x)))