How to align geom_repel_text to geom_jitter points when subsetting the data?

Viewed 774

I am making boxplots and jitter to show each individual point. I am then putting text labels on each point. This works fine but as soon as I try to subset which points I want label, the text doesn't align any longer.

Here is my code (with some help from this page): Aligning geom_text to geom_jitter points

library(ggplot2)
ggplot(mtcars, aes(vs, wt, group = am, label = wt)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(position = position_jitter(seed = 1)) +
  geom_text_repel(data = subset(mtcars, wt > 3),
                  position = position_jitter(seed = 1))

Here is my plot. As you can see the labels are not aligned with the points. boxplot with jitter and subsetted labels

Any ideas why this doesn't work?

2 Answers

The issue is that by subsetting ggrepel will only see this part of your data and assumes that your are only plotting the subset. If you want ggrepel to take account of all your data use an ifelse condition to select the points you want to label instead of subsetting:

library(ggplot2)
library(ggrepel)
ggplot(mtcars, aes(vs, wt, group = am, label = wt)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(position = position_jitter(seed = 1)) +
  geom_text_repel(aes(label = ifelse(wt > 3, wt, "")), position = position_jitter(seed = 1))

An alternative is to use a custom alpha to make the weights you don't want to display invisible:

library(ggplot2)

ggplot(within(mtcars, visible <- wt > 3),
       aes(vs, wt, group = am, label = wt)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(position = position_jitter(seed = 1)) +
  geom_text_repel(position = position_jitter(seed = 1),
                  aes(alpha = visible)) +
  scale_alpha_manual(values = c(0, 1)) +
  guides(alpha = guide_none())

enter image description here

Related