Home > Net >  How to add captions outside the plot on individual facets in ggplot2?
How to add captions outside the plot on individual facets in ggplot2?

Time:03-22

I am trying to add a caption in each facet (I am using facet_grid). I have seen these enter image description here

Is it possible to have something like this? (caption OUTSIDE the plot) (but without the previous warning)

a   labs(caption = c("nonchilled=4", "chilled=6"))   theme(plot.caption = element_text(hjust=c(0, 1)))

enter image description here

NOTE: This is only an example, but I may need to put long captions (sentences) for each plot. Example:

a   labs(caption = c("This is my first caption that maybe it will be large. Color red, n= 123", "This is my second caption that maybe it will be large.  Color blue, n= 22"))   
  theme(plot.caption = element_text(hjust=c(1, 0)))

Does anyone know how to do it?

Thanks in advance

CodePudding user response:

You need to add the same faceting variable to your additional caption data frame as are present in your main data frame to specify the facets in which each should be placed. If you want some facets unlabelled, simply have an empty string.

caption_df <- data.frame(
  cyl = c(4, 6, 8, 10),
  conc = c(0, 1000, 0, 1000),
  Freq = -1,
  txt = c("1st=4", "2nd=6", '', ''),
  Type = rep(c('Quebec', 'Mississippi'), each = 2),
  Treatment = rep(c('chilled', 'nonchilled'), 2) 
)

a   coord_cartesian(clip="off", ylim=c(0, 3), xlim = c(0, 1000))  
  geom_text(data = caption_df, aes(y = Freq, label = txt))  
  theme(plot.margin = margin(b=25))

enter image description here

  • Related