R ggplot2 ggrepel - label a subset of points while being aware of all points
You can try the following:
- Assign a blank label (
""
) to all the other points from the original data, so thatgeom_text_repel
takes them into consideration when repelling labels from one another; - Increase the
box.padding
parameter from the default0.25
to some larger value, for greater distance between labels; - Increase the x and y-axis limits, to give the labels more space at the four sides to repel towards.
Example code (with box.padding = 1
):
ggplot(dt, aes(x = one, y = two, color = diff_cat)) + geom_point() + geom_text_repel(data = . %>% mutate(label = ifelse(diff_cat %in% c("type_1", "type_2") & abs(diff) > 2, name, "")), aes(label = label), box.padding = 1, show.legend = FALSE) + #this removes the 'a' from the legend coord_cartesian(xlim = c(-5, 5), ylim = c(-5, 5)) + theme_bw()
Here's another attempt, with box.padding = 2
:
(Note: I'm using ggrepel 0.8.0. I'm not sure if all the functionalities are present for earlier package versions.)