ℕʘʘḆḽḘ
ℕʘʘḆḽḘ

Reputation: 19375

How to use the first value of a column as a subtitle in ggplot?

Consider this simple chart

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

Here, I would like to show the string shown in the title column (as you can see, it is always the same for each group) on a subtitle for each chart.

I tried to play with labs(subtitle = .$title[[1]]) but that says Error in labs(subtitle = .$title[[1]]) : object '.' not found

Any ideas? Thanks!

Upvotes: 1

Views: 422

Answers (1)

Marius
Marius

Reputation: 60080

You can paste the titles to combine them with the group labels, and use that as the facet label:

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)

Upvotes: 1

Related Questions