r - 如何使用 ggplot 中的分组箱线图将 geom_text 标签放置在正确的位置

标签 r ggplot2

在这种情况下,我在 iris 数据框中添加了一个分组变量。我希望按物种制作 Sepal.Length 的箱线图,并用带有标签标识的异常值的分组变量填充。这一切都有效,但是当我尝试用 geom_text 标记离群值时,它们现在使用分组位置打印,而不是在中心打印。似乎 geom_text 没有继承全局 aes() 但我不知道为什么。

代码:

library(tidyverse)
# function to id outlier
is_outlier <- function(x) {
  return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x))
}

# make a grouping variable
iris$group <- sample(1:3, nrow(iris),replace = T)

# make a outlier variable
iris <- 
  iris %>%
  group_by(Species, group) %>%
  mutate(outlier = ifelse(is_outlier(Sepal.Length), Sepal.Length, as.numeric(NA)))
iris$outlier

# graph
iris %>%
  ggplot(aes(x = Species,y = Sepal.Length, fill = factor(group))) +
  geom_boxplot() +
  geom_text(aes(label = outlier))

标签位于中心,而不是在各自的框上方。这是怎么回事?

最佳答案

这是因为一旦你有了组,就会在箱线图中躲避。使用 position_dodge明确地控制它。您可能想在 geom_text 中尝试使用 hjustvjust 参数来避免绘制超过点。

iris %>%
  ggplot(aes(x = Species,y = Sepal.Length, fill = factor(group))) +
  geom_boxplot(position = position_dodge(width = 1)) +
  geom_text(aes(label = outlier), position = position_dodge(width = 1))

enter image description here

关于r - 如何使用 ggplot 中的分组箱线图将 geom_text 标签放置在正确的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58528380/

相关文章:

R ggplot2 与 shapefile 和 csv 数据合并以填充多边形

r - 如何将表格添加到我的 ggplot2 输出?

r - 自定义多面条形图的美学

r - 在 Shiny for R 中,为什么 Sys.Date() 在 dateInput 中返回昨天的日期?

r - 奇怪的警告消息 : In FUN(X[[i]], ...) :强制引入的 NA

python - Rpy2,将R返回(List Vector)转换为Python中的Json对象

r - Shiny 服务器: leafet doesn't display viridis colors in legend

r - 在 R 中创建交错图表

r - ggplot 省略了多边形孔

r - 如何在 GGPLOT theme_classic() 中启用 x 轴和 y 轴