Pablo Pretzel
Pablo Pretzel

Reputation: 158

R - when using facet_wrap, access the factor within the current facet

Consider the following (nonsensical, but working) plot:

ggplot(mtcars,                                                                                                                          
       aes(x = as.factor(cyl), y = hp)) +                                                                          
       geom_boxplot() +                                                                                                                                                                     
       facet_wrap( ~ am) +                                                                                             
       geom_text(label = "test")

Nonsensical graph

I'd like to pass the value of am within each facet to the label argument of geom_text. So all the labels within the left facet would read "0", all the labels within the right facet would read "1".

How could I achieve this? Simply passing am doesn't work, and neither does .$am.

Upvotes: 0

Views: 63

Answers (2)

Quinten
Quinten

Reputation: 41285

You could pass it as a vector like this:

library(ggplot2)
ggplot(mtcars, aes(x = as.factor(cyl), y = hp)) +                                                                          
  geom_boxplot() +  
  facet_wrap( ~ am) +
  geom_text(label = mtcars$am) 

Created on 2022-11-03 with reprex v2.0.2

Upvotes: 0

langtang
langtang

Reputation: 24722

Sure, just provide the label inside mapping, like this:

  ... + 
  geom_text(aes(label = am))

Upvotes: 1

Related Questions