如何在ggplot2中组合排斥标签和阴影或光晕文本? [英] How to combine repelling labels and shadow or halo text in ggplot2?

查看:56
本文介绍了如何在ggplot2中组合排斥标签和阴影或光晕文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于ggplot2中的任一标签都有一些不错的解决方案(例如

我们如何获得与 geom_text_repel 一起使用的阴影文字?我

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)

这篇关于如何在ggplot2中组合排斥标签和阴影或光晕文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆