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:
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?)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With