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

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

我经常像上面的示例中那样创建图以仅绘制子集,并且希望为该子集自动标注。目前,在.中无法识别ggtitle,但在geom_text中可以正常使用。

编辑:
由于我得到了一个很好的注释,并从@Brian标记为重复,因此是否有解决方案可以在{}函数中使用此dplyr::group_by技巧?这在某种程度上是行不通的。我想为每个组创建单独的图,但是不知何故,只有完整的数据框才进入ggplot调用。
mpg %>%
  group_by(manufacturer) %>% {
    ggplot(., aes(cyl, displ, color=manufacturer)) +
      geom_point() +
      ggtitle(unique(.$manufacturer))
  }

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

最佳答案

我将尝试以下操作,因为无法在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))

r - 在ggtitle中访问图的数据-LMLPHP

想法是使用带有空带背景的构面。如果有更多的名称或变量,则必须使用例如来创建一个额外的构面变量。 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))

编辑

如您所问的第二个问题,这是为每个组创建单独图的两种解决方案
# 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

或使用保存数据
map2(paste0(p$manufacturer, ".pdf"), p$plots, ggsave)

关于r - 在ggtitle中访问图的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49631795/

10-12 17:34
查看更多