0

I am facing a smal issue concerning positioning labels on an R graph. I made an example with the data available in ggplot2 package to make it executable.

library(ggrepel)
library(ggplot2)
library(tidyverse)

pos <- position_jitter(seed = 1, height = 0.25)
ggplot(mtcars, aes(vs, wt, group = am, label = wt)) +
  geom_jitter(position = pos) +
  geom_text_repel(aes(label = ifelse(wt > 3, wt, "")), position = pos)

I used the command position_jitter to define jitter and geom_text_repel to set data labels. Using position_jitter I cannot define a position nudge_y of data labels but I woukld like to add to the defined position (position_jitter(seed = 1, height = 0.25)) a fixed value, let's say +0.5, so as to shift up systematically every label of a defined value.

Is it possible to make in R something like this?

Thank you in advance for every your reply!

Phil
  • 7,287
  • 3
  • 36
  • 66
GiacomoDB
  • 369
  • 1
  • 10
  • Wouldn't this be as simple as just using `aes(y = wt + 0.5, label = ifelse(wt > 3, wt, ""))` in the repel layer? – teunbrand Sep 03 '21 at 15:02
  • I see it works, but it is not a 100% good solution because you miss the connecting line label-dot. If the dot is distant from the label, there should be a connecting line between the two to indicate which label refers to. Why you put `y = wt + 0.5` into the aesthetic? Because there, you are defining the y position of the labels? – GiacomoDB Sep 03 '21 at 15:34
  • Yes, layers normally inherit aesthetics from the global call to `ggplot()`. However, if you set aesthetics in a layer, they overrule aesthetics from the global plot. – teunbrand Sep 03 '21 at 15:37
  • Besides this, it's a pity the line missing. – GiacomoDB Sep 03 '21 at 15:38
  • 1
    Another way to get rid of the problem is to add jitter manually before feeding data to ggplot2. Then you can just use `ggrepel::position_nudge_repel()`. – teunbrand Sep 03 '21 at 15:41
  • Can you write an example simplified code? – GiacomoDB Sep 03 '21 at 20:22

1 Answers1

1

RE: comments

You can manually add jitter (random uniform) noise to your datapoints beforehand. Nudging the text then becomes trivial.

library(ggrepel)
library(ggplot2)
library(tidyverse)

mtcars %>%
  mutate(jit_vs = vs + runif(length(vs), -0.4, 0.4),
         jit_wt = wt + runif(length(wt), -0.25, 0.25)) %>%
  ggplot(aes(jit_vs, jit_wt, group = am, label = wt)) +
  geom_point() +
  geom_text_repel(aes(label = ifelse(wt > 3, wt, "")), nudge_y = 0.5)

Created on 2021-09-03 by the reprex package (v2.0.1)

teunbrand
  • 33,645
  • 4
  • 37
  • 63