使用 geom_text 和 facet_grid 时在箱线图上显示紧凑字母

Displaying compact letters over box plot when using geom_text and facet_grid

这是我的第一个问题,如果我没有把 problem/example 说清楚,我很抱歉!

我正在尝试使用 ggplot2 制作一个箱线图,每个箱线图上都显示紧凑的字母。当情节没有分面时,我可以实现这一点,但是,当我用 facet_grid 分割情节时,每个方面未使用的水平显示没有箱线图,只有一个字母。当我在分面图上没有标签时,不会出现空水平。

这是我的一部分数据的示例:

# Dataframe structure
df <- structure(list(Var1 = c("A", "A", "A", "A", "A", "A", "A", "A", 
"A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "C", "C", "C", 
"C", "C", "C"), Var2 = c("D", "E", "F", "G", "H", "K", "L", "M", 
"N", "O", "P", "Q", "R", "W", "X", "Y", "Z", "AA", "BB", "CC", 
"DD", "EE", "FF", "GG"), Freq = c(0.80150902033661, 0.781994333507093, 
0.799306241892755, 0.792266624114348, 0.828044075178601, 0.848185700561263, 
0.835649227456286, 0.801230470031423, 0.838080218109771, 0.799543499023431, 
0.803041227907527, 0.843425895355166, 0.807979849825537, 0.831781069908856, 
0.828458207462573, 0.846052247644906, 0.858664022176908, 0.82399256530848, 
0.847625303767408, 0.799364138073169, 0.846301760577181, 0.801491930111703, 
0.816622607179678, 0.848192570263525), Type = c("H.Tree", "H.Tree", 
"H.Tree", "H.Tree", "H.Tree", "H.Tree", "H.Grass", "H.Grass", 
"H.Grass", "H.Grass", "H.Grass", "H.Grass", "R.Tree", "R.Tree", 
"R.Tree", "R.Tree", "R.Tree", "R.Tree", "R.Grass", "R.Grass", 
"R.Grass", "R.Grass", "R.Grass", "R.Grass"), Time = c("Old", 
"Old", "Old", "Old", "Old", "Old", "Old", "Old", "Old", "Old", 
"Old", "Old", "New", "New", "New", "New", "New", "New", "New", 
"New", "New", "New", "New", "New")), class = "data.frame", row.names = c(NA, 
-24L))

df.labels <- structure(list(Type = c("R.Grass", "R.Tree", "H.Grass", "H.Tree"
), Letter = c("a", "b", "ab", "c")), class = "data.frame", row.names = c(NA, -4L))

# Boxplot not faceted
ggplot(df, aes(x=Type, y=Freq)) + geom_boxplot(fill="lightgrey", color = "black") +
  geom_text(data=df.labels, aes(label = Letter, x = Type, y = 0.88))

Image of non-facet boxplot


# Faceted boxplot 
ggplot(df, aes(x=Type, y=Freq)) + geom_boxplot(fill="lightgrey", color = "black") +
  facet_grid(~Time, scales = "free_x")+
  geom_text(data=df.labels, aes(label = Letter, x = Type, y = 0.88)) 
 

Image of facet boxplot

我想也许在 geom_text 部分添加 inherit.aes 会起作用,但没有帮助

geom_text(data=df.labels, aes(label = Letter, x = Type, y = 0.88), inherit.aes = FALSE)

如有任何建议,我们将不胜感激

正如@27 ϕ 9 所建议的那样,将其添加到标签数据框架中是可行的

df.labels$Time <- c("New", "New", "Old", "Old")