r - 使用 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)
我们欢迎所有的建议
解决方案
正如@27 φ 9 建议的那样,将其添加到标签数据框中是可行的
df.labels$Time <- c("New", "New", "Old", "Old")
推荐阅读
- php - URL 重写:完全防止重写现有资源
- php - laravel model save() 将重复的数据保存在数据库中
- database - 当 2 个事务更新记录而一个回滚时会发生什么?
- typescript - 使用打字稿时在Vue项目中注册第三方包
- c# - 将模型从 Ajax (BeginForm) 传递到控制器时,模型始终为空
- mongodb - 如何限制组查询中返回的对象数量
- java - 如何将位图保存在缓存中并从缓存中共享?
- php - 创建一个查询,检查数量是否在数量范围之间,并在 laravel 中使用 jquery 从产品 ID 输出一定数量的基础
- php - 如何按字母顺序对转发器字段进行排序?ACF
- oracle - 无法为 hr 表创建 localhost 连接