如何在 ggplot2 的各个方面的情节外添加字幕?

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

我正在尝试在每个方面添加一个 caption(我正在使用 facet_grid)。我看过这些 approach and this : 但没有任何东西能满足我的需求。此外,第一种方法 returns 一条警告消息表明我没有找到任何解决方案:

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

我的例子:

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))

我们的想法是每个绘图有 1 个标题,但使用这种方法会重复标题并被覆盖。

有没有可能有这样的东西? (情节外的标题)(但没有之前的警告)

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

注意:这只是一个示例,但我可能需要为每个情节添加长标题(句子)。 示例:

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)))

有人知道怎么做吗?

提前致谢

您需要将与主数据框中存在的相同的分面变量添加到附加标题数据框中,以指定应放置每个分面的分面。如果您想要一些未标记的方面,只需使用一个空字符串即可。

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))