Closed
Description
In the example below, I would expect all of the text labels to be positioned perfectly on top of the data points. Instead, some of the text labels are not positioned correctly.
I think the issue is due to position_dodge()
. I'm not sure exactly where to look to find the relevant code.
In the last example, I use ggrepel to help illustrate the problem more clearly. You can see the blue labels 34
and 290
are not pointing to the correct positions. It seems like they're pointing to the "undodged" positions instead of the "dodged" positions.
This issue was originally reported by @raviselker in ggrepel issues: slowkow/ggrepel#122
library(tidyverse)
library(ggrepel)
# remotes::install_github("thomasp85/patchwork)
library(patchwork)
set.seed(1337)
df <- tibble(
x = rnorm(500),
g1 = factor(sample(c("A", "B"), 500, replace = TRUE)),
g2 = factor(sample(c("A", "B"), 500, replace = TRUE)),
rownames = 1:500
)
is_outlier <- function(x) {
return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x))
}
df_outliers <- df %>% group_by(g1, g2) %>% mutate(outlier = is_outlier(x))
p1 <- ggplot(df_outliers, aes(x = g1, y = x, fill = g2)) +
geom_boxplot(width = 0.3, position = position_dodge(0.5))
p2 <- p1 +
geom_text(
data = . %>% filter(outlier),
mapping = aes(label = rownames),
position = position_dodge(0.5)
)
p1 + p2
ggplot(df_outliers, aes(x = g1, y = x, fill = g2)) +
geom_boxplot(width = 0.3, position = position_dodge(0.5)) +
ggrepel::geom_label_repel(
min.segment.length = 0,
data = . %>% filter(outlier),
mapping = aes(label = rownames),
position = position_dodge(0.5)
)
Created on 2018-12-02 by the reprex package (v0.2.1)