7

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?)

4

1 回答 1

4

这个功能现在已经添加到 ggrepel 包中了,太棒了!

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)

在此处输入图像描述

于 2020-08-19T17:16:01.923 回答