0

I have a boxplot graph where I want to show label names. The problem is that I want to repel these label names to make them beyond the boxplot. I tried geom_text_repel from ggrepel package but it repels lables when they overlap each other.

Also tried advice like this: Repel geom label and text in ggplot. And ordering geom points based on size

And have not received any comprehensive info about solving my problem.

Sample:

mtdata <- mtcars %>%
  rownames_to_column(var = "name") %>%
  mutate(cyl = as.factor(cyl))

ggplot(mtdata, aes(x = cyl, y = mpg)) + geom_boxplot() +
  geom_text_repel(data = mtdata %>%
               filter(mpg > 20 & wt >3), aes(label = name))

Desirable output:

enter image description here

So, you can see that there is a dot which depicts exact label position and repelling.

rg4s
  • 811
  • 5
  • 22

1 Answers1

1

A cheeky solution would be a simple nudge.

library(tidyverse)
mtdata <- mtcars %>%
  rownames_to_column(var = "name") %>%
  mutate(cyl = as.factor(cyl))

ggplot(mtdata, aes(x = cyl, y = mpg)) + geom_boxplot() +
  ggrepel::geom_text_repel(data = mtdata %>%
                    filter(mpg > 20 & wt >3), aes(label = name), nudge_x = .75)

Created on 2021-02-08 by the reprex package (v0.3.0)

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • Thank you very much, @tjebo! This one helped me. May be you also know whether it is possible to make lables fontface bold? I've tried ```theme(text = element_text(face="bold")``` but it did not work. – rg4s Feb 08 '21 at 14:46
  • @k1rgas see maybe my answer to your previous question, I am sure you can do that with the ggtext package as well – tjebo Feb 08 '21 at 14:49
  • https://stackoverflow.com/questions/66101889/how-can-i-rotate-labels-in-ggplot2/66102495#66102495 for future reference – tjebo Feb 08 '21 at 14:50
  • ok, got you. Unfortunately, it does not fit me. But thanks! – rg4s Feb 08 '21 at 14:50