1

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()
dagcilibili
  • 461
  • 5
  • 11
  • It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that can be used for testing and validating possible solutions. – MrFlick Oct 04 '17 at 19:17
  • I am working on making one, thank you very much for the feedback. – dagcilibili Oct 04 '17 at 19:20
  • 1
    What happens if, first plot subset with `geom_text` without repel, then the ones we want to repel, use `geom_text_repel()`? Does it get plotted over existing text from `geom_text`, or it *knows* and avoids overlap from previous layer? – zx8754 Oct 04 '17 at 19:37
  • Unfortunately it does not work. I have added a reproducible example for testing. – dagcilibili Oct 04 '17 at 20:32

0 Answers0