Home > Back-end >  R - when using facet_wrap, access the factor within the current facet
R - when using facet_wrap, access the factor within the current facet

Time:11-04

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.

CodePudding user response:

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

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

CodePudding user response:

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

  • Related