在ggtitle中访问图的数据

drm*_*iod 5 r ggplot2 ggtitle

我想知道是否可以通过某种方式访问ggplot2标题图中提供的数据的列。所以像这样:

ggplot(mpg %>% filter(manufacturer == 'audi'), 
  aes(x = hwy, y = displ, label = model)) + 
    geom_point() + 
    geom_text(data = . %>% filter(hwy > 28)) + 
    ggtitle(unique(.$manufacurer))
Run Code Online (Sandbox Code Playgroud)

我经常像上面的示例中那样创建图以仅绘制子集,并且希望为该子集自动标注。目前,.不会在内识别出,ggtitle而是在geom_text其中起作用。

编辑:
由于我得到了一个很好的注释,并从@Brian标记为重复项,是否有解决方案可以{}在dplyr::group_by函数中使用此技巧?这不起作用。我很乐意为每个组创建单独的图,但是不知何故,只有完整的数据框可以ggplot调用。

mpg %>%
  group_by(manufacturer) %>% {
    ggplot(., aes(cyl, displ, color=manufacturer)) +
      geom_point() + 
      ggtitle(unique(.$manufacturer))
  }
Run Code Online (Sandbox Code Playgroud)

它说奥迪,但在单个图中打印所有制造商。

Rom*_*man 4

我会尝试以下操作,因为无法通过管道传输到外部aes()。

ggplot(mpg %>% filter(manufacturer == 'audi'), 
       aes(x = hwy, y = displ, label = model)) + 
  geom_point() + 
  geom_text(data = . %>% filter(hwy > 28)) +
  facet_wrap(~manufacturer)+
  theme(strip.background = element_blank(),
        strip.text = element_text(hjust = 0, size = 14))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这个想法是使用带有空条背景的小面。如果有更多名称或变量,则必须使用例如创建一个额外的分面变量mutate(gr = "title")

mpg %>% 
  mutate(title="This is my plot") %>% 
ggplot(aes(x = hwy, y = displ, col=manufacturer)) + 
  geom_point() + 
  facet_wrap(~title)+
  theme(strip.background = element_blank(),
        strip.text = element_text(hjust = 0, size = 14))
Run Code Online (Sandbox Code Playgroud)

编辑

当您问第二个问题时,这里有两种为每个组创建单独图的解决方案

# first solution
p <- mpg %>%
  group_by(manufacturer) %>% 
     do(plots= ggplot(., aes(cyl, displ)) +
      geom_point() + 
      ggtitle(unique(.$manufacturer))
   )
p %>% slice(1) %>% .$plots


# second solution
mpg %>%
  nest(-manufacturer) %>%
  mutate(plot = map2(data, manufacturer, ~ggplot(data=.x,aes(cyl, displ))+
           geom_point() +
           ggtitle(.y))) %>% 
  slice(1) %>% .$plot 
Run Code Online (Sandbox Code Playgroud)

或者使用保存数据

map2(paste0(p$manufacturer, ".pdf"), p$plots, ggsave)
Run Code Online (Sandbox Code Playgroud)