首页 > 解决方案 > 使用 geom_text 和 facet_grid 时在箱形图上显示紧凑字母

问题描述

这是我的第一个问题,所以如果我没有把问题/例子说清楚,我很抱歉!

我正在尝试使用 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))

非分面箱线图的图像


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

分面箱线图的图像

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

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

我们欢迎所有的建议

标签: rggplot2facet-gridgeom-text

解决方案


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

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

推荐阅读