Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 637
Stonecraft Avatar asked Feb 08 '18 18:02

Stonecraft


People also ask

How do I repel labels in ggplot2?

ggrepel provides geoms for ggplot2 to repel overlapping text labels: geom_text_repel() geom_label_repel()

What is geom_text_repel?

Description. geom_text_repel adds text directly to the plot. geom_label_repel draws a rectangle underneath the text, making it easier to read. The text labels repel away from each other and away from the data points.


1 Answers

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

like image 71
Kamil Slowikowski Avatar answered Sep 24 '22 04:09

Kamil Slowikowski