如何控制显示哪些facet_wrap标签

Rya*_*yan 5 r facet ggplot2 facet-wrap

在下面使用 时facet_wrap, 和yearmodel显示在绘图标签中。

library(tidyverse)
mpg %>%
  filter(manufacturer=='audi')%>%
  ggplot(aes(cty, hwy)) + 
  geom_point(aes(col = model)) +
  facet_wrap(year~model)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我们已经为点着色model并显示在图例中,因此我们实际上不需要model每个方面标签。model我们怎样才能从标签上删除呢?

MrF*_*ick 6

最简单的方法是调整标签功能以仅提取第一个变量的标签。你可以这样做

mpg %>%
  filter(manufacturer=='audi')%>%
  ggplot(aes(cty, hwy)) + 
  geom_point(aes(col = model)) +
  facet_wrap(~year+model, labeller=function(x) {x[1]})
Run Code Online (Sandbox Code Playgroud)

另一种方法是创建一个交互变量,这样您只需对一个变量进行分面,然后您可以更改贴标器以删除第二个值的名称。那看起来像这样

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)))
Run Code Online (Sandbox Code Playgroud)

小平面条中没有模型名称的绘图