如何使用列的第一个值作为ggplot中的字幕?

时间:2018-09-17 00:53:41

标签: r ggplot2

考虑这个简单的图表

library(ggplot2)

data_frame(group = c('a', 'a', 'b', 'b'),
           x = c(1,2,3,4),
           y = c(10,11,12,13),
           title = c('one', 'one', 'two', 'two')) 

# A tibble: 4 x 4
  group     x     y title
  <chr> <dbl> <dbl> <chr>
1 a         1    10 one  
2 a         2    11 one  
3 b         3    12 two  
4 b         4    13 two 

%>% 
  ggplot(aes(x = x, y = y, group = group)) + geom_point(size = 12)+ 
  facet_wrap(~group)

enter image description here

在这里,我想在每个图表的副标题上显示title列中显示的字符串(如您所见,对于每个组它始终是相同的)。

我尝试过玩labs(subtitle = .$title[[1]]),但是说Error in labs(subtitle = .$title[[1]]) : object '.' not found

有什么想法吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

您可以paste将标题与组标签结合起来,并将其用作构面标签:

data_frame(group = c('a', 'a', 'b', 'b'),
           x = c(1,2,3,4),
           y = c(10,11,12,13),
           title = c('one', 'one', 'two', 'two')) %>% 
    mutate(group_title = paste0(group, "\n", title)) %>%
    ggplot(aes(x = x, y = y, group = group)) + geom_point(size = 12)+ 
    facet_wrap(~group_title)