Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine repelling labels and shadow or halo text in ggplot2?

Tags:

r

ggplot2

ggrepel

There are some nice solutions for either repelling labels in ggplot2 (e.g. ggrepel) or shadow text for labels (e.g. ggshadowtext and this answer). But nothing that allows us to combine these two functions.

I tried this hack that prints the labels many times in slightly different locations, but it doesn't go well with geom_text_repel

library(ggplot2)

# subset data
d <- diamonds[1:20,]

# make plot
p <- ggplot(d, aes(carat, price)) +
  geom_point()

# make halo layers
theta <- seq(pi / 8, 2 * pi, length.out = 16)
xo <- diff(range(d$carat)) / 200
yo <- diff(range(d$price)) / 200
for (i in theta) {
  p <- p + 
    geom_text_repel(data = d, 
              aes_q(x = bquote(carat + .(cos(i) * xo)),
                    y = bquote(price + .(sin(i) * yo)),
                    label = ~cut),
              size = 6,
              colour = 'black', 
              seed = 1,
              segment.colour = NA)
}

# update plot with halo and interior text
p <- p + geom_text_repel(aes(label = cut),
                   size = 6,
                   colour = 'white', 
                   seed = 1,
                   segment.colour = "grey80")

p

It is very slow, and in the locations where the labels are close, this method is not effective:

enter image description here

How can we get shadow text that works with geom_text_repel? I posted an issue about this to the ggrepel GitHub repo some time ago, but there has been no reply (perhaps it's impossible?)

like image 624
Ben Avatar asked Jun 27 '19 21:06

Ben


1 Answers

This feature has now been added to the ggrepel package, and it is awesome!

library(ggrepel)
library(ggplot2)

dat <- mtcars
dat$car <- rownames(dat)

ggplot(dat) +
  aes(wt, 
      mpg, 
      label = car) +
  geom_point(colour = "red") +
  geom_text_repel(bg.color = "white",
                  bg.r = 0.25)

enter image description here

like image 76
Ben Avatar answered Nov 12 '22 16:11

Ben