Search code examples
rggplot2positiongeom-textggrepel

Text repel with a position argument in ggplot/R


I am trying to make a geom_point where the text labels both repel, and point to their associated points even if I am using position=dodge or position=jitter. I also have a lot of points to label, which is why I want to use ggrepel or something similar. My understanding is that I cannot use the position argument for ggrepel.

Is there any way I can get a plot like this, except with the segments pointing to their associated points?

require(ggplot2)
require(ggrepel)
data("mtcars")
mtcars$cyl <- as.factor(mtcars$cyl)
mtcars$am <- as.factor(mtcars$am)

require(ggplot2)
require(ggrepel)
dodge = position_dodge(1)
ggplot(mtcars, aes(x = am, y=mpg)) +
  geom_point(size=3, position=dodge, alpha=0.5, aes(color=cyl)) +
  geom_text_repel(data = mtcars,
                  aes(label = mpg, x=am, y=mpg),  alpha=0.9, size=4,
                  segment.size = .25, segment.alpha = .8, force = 1)

enter image description here


Solution

  • Today, I updated ggrepel to support the position option in version 0.7.3.

    Please try it out and let me know how it goes.

    If you have issues, please report them here: https://github.com/slowkow/ggrepel/issues

    Install version 0.7.3 of ggrepel:

    devtools::install_github("slowkow/ggrepel")
    

    Let's try it:

    require(ggplot2)
    require(ggrepel)
    data("mtcars")
    mtcars$cyl <- as.factor(mtcars$cyl)
    mtcars$am <- as.factor(mtcars$am)
    
    dodge <- position_dodge(1)
    ggplot(mtcars, aes(x = am, y = mpg, label = mpg)) +
      geom_point(
        mapping = aes(color = cyl),
        position = dodge,
        size = 3,
        alpha = 0.5
      ) +
      geom_text_repel(
        mapping = aes(group = cyl),
        position = dodge,
        size = 4,
        alpha = 0.9,
        segment.size = .25,
        segment.alpha = .8,
        force = 1
      )
    

    ggrepel with position