0

I am trying to add a caption in each facet (I am using facet_grid). I have seen these approach and this one: but nothing gives me what I need. Also, the first approach returns a warning message that I didn't find any solution:

Warning message:
Vectorized input to `element_text()` is not officially supported.
Results may be unexpected or may change in future versions of ggplot2.

My example:

library(ggplot2)
library(datasets)

mydf <- CO2
a <- ggplot(data = mydf, aes(x = conc)) + geom_histogram(bins = 15, alpha = 0.75) +
  labs(y = "Frequency") + facet_grid(Type ~ Treatment) 
a

caption_df <- data.frame(
  cyl = c(4,6),
  txt = c("1st=4", "2nd=6")
)

a + coord_cartesian(clip="off", ylim=c(0, 3)) +
  geom_text(
    data=caption_df, y=1, x=100,
    mapping=aes(label=txt), hjust=0,
    fontface="italic", color="red"
  ) +
  theme(plot.margin = margin(b=25))

The idea is to have 1 caption per plot, but with this approach it repeats the caption and it is overwritten. 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

emr2
  • 1,436
  • 7
  • 23

1 Answers1

1

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

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Thanks very much for your help. However, I would like to have the captions OUTSIDE the plot, as I explained at the end of the post and in the title of the question. I don't want to have them inside the plot. Do you know if it is possible? (sorry for the disturbance) – emr2 Mar 21 '22 at 12:48
  • Also, I would like to have 1 caption per plot. That is: one for chilled and another one for nonchilled. – emr2 Mar 21 '22 at 12:50