I have a set of text to be printed using ggplot
at (x,y) locations where only a subset of them overlaps. I would like to keep the ones not overlapping exactly where they are and then repel the ones that overlap (I know which ones do these -- for example the names of states in New England overlap while in the west nothing overlaps, I want to keep the western state names where they are but repel the ones in New England). When I use the geom_text_repel
it repels all of the text. If I chose the subset that does not overlap and use geom_text
to print them and the other using geom_text_repel
because they are at different layers. Is there a way to fix some subset of text and repel the rest using geom_text_repel
or do I need to go for a completely different solution?
Here is an example:
library(tidyverse)
library(ggrepel)
# state centers by fixing Alaska and Hawaii to look good in our maps
df = data.frame(x = state.center$x, y= state.center$y, z = state.abb)
overlaps = c('RI', 'DE', 'CT', 'MA')
df %>%
ggplot() +
geom_point(aes(x,y),
size = 1) +
# plot the ones I would like to keep where the are
# I want these right centered around the points
geom_text(aes(x,y,label=z),
data = df %>% filter(! z %in% overlaps),
size = 4) +
# plot the ones I would like to repel
geom_text_repel(aes(x,y,label=z),
data = df %>% filter(z %in% overlaps),
size = 4,
min.segment.length = unit(0, "npc")) +
coord_map() +
theme_minimal()
df %>%
ggplot() +
geom_point(aes(x,y),
size = 1) +
# if we repel all instead
geom_text_repel(aes(x,y,label=z),
size = 4,
min.segment.length = unit(0, "npc")) +
coord_map() +
theme_minimal()