调整geom_richtext的背景Alpha

hyrbngr7  于 2023-01-03  发布在  其他
关注(0)|答案(2)|浏览(84)

下面是ggplot(来自https://wilkelab.org/ggtext/reference/geom_richtext.html

library(ggplot2)

df <- data.frame(
  label = c(
    "Some text **in bold.**",
    "Linebreaks<br>Linebreaks<br>Linebreaks",
    "*x*<sup>2</sup> + 5*x* + *C*<sub>*i*</sub>",
    "Some <span style='color:blue'>blue text **in bold.**</span><br>And *italics text.*<br>
      And some <span style='font-size:18pt; color:black'>large</span> text."
  ),
  x = c(.2, .1, .5, .9),
  y = c(.8, .4, .1, .5),
  hjust = c(0.5, 0, 0, 1),
  vjust = c(0.5, 1, 0, 0.5),
  angle = c(0, 0, 45, -45),
  color = c("black", "blue", "black", "red"),
  fill = c("cornsilk", "white", "lightblue1", "white")
)

ggplot(df) +
  aes(
    x, y, label = label, angle = angle, color = color, fill = fill,
    hjust = hjust, vjust = vjust
  ) +
  geom_richtext() +
  geom_point(color = "black", size = 2) +
  scale_color_identity() +
  scale_fill_identity() +
  xlim(0, 1) + ylim(0, 1)

我想给label的背景增加一些透明度。当我应用alpha = 0.30时,* 文本和背景 * 都会受到影响。有什么方法可以调整alpha的背景吗?
@stefan建议使用scales::alpha,但在以下情况下不起作用

library(ggplot2)
library(ggtext)

ggplot(data.frame(x = c(-2, 2)), aes(x = x)) +
    stat_function(fun = dnorm) +
    geom_richtext(data = data.frame(x = c(-1.4, -.5), y = rep(dnorm(0, 2)), y1 = c('First', 'Second')),
                    aes(x = x, y = y, label = y1, fill = alpha(y1, 0.2))) +
    scale_fill_manual(breaks = c('First', 'Second'), values = c('#c1121f', '#023e8a'), aesthetics = 'fill')

有了这个,我得到下面的错误

Error: Unknown colour name: First
juud5qan

juud5qan1#

一个选项是使用scales::alpha设置填充颜色的alpha:

library(ggplot2)
library(ggtext)

ggplot(df) +
  aes(
    x, y, label = label, angle = angle, color = color, fill = fill,
    hjust = hjust, vjust = vjust
  ) +
  geom_richtext(aes(fill = alpha(fill, 0.30))) +
  geom_point(color = "black", size = 2) +
  scale_color_identity() +
  scale_fill_identity() +
  xlim(0, 1) + ylim(0, 1)

编辑对于您的第二个示例,我们可以或必须在fill量表的values上应用scales::alpha。然而,只有在geom_richtext中使用fill aes时,这才有效。如果不是这种情况,当然,我们仍然可以在ggnewscale包中同时应用这两种方法中的一种。

library(ggplot2)
library(ggtext)

ggplot(data.frame(x = c(-2, 2)), aes(x = x)) +
  stat_function(fun = dnorm) +
  geom_richtext(
    data = data.frame(x = c(-1.4, -.5), y = rep(dnorm(0, 2)), y1 = c("First", "Second")),
    aes(x = x, y = y, label = y1, fill = y1)
  ) +
  scale_fill_manual(
    breaks = c("First", "Second"),
    values = alpha(c("#c1121f", "#023e8a"), .2),
    aesthetics = "fill"
  )

wqlqzqxt

wqlqzqxt2#

下面是一个替代方法:根据documentation of ggtext

library(ggplot2)
library(ggtext)

ggplot(df) +
  aes(
    x, y, label = label, angle = angle, color = color,
    hjust = hjust, vjust = vjust
  ) +
  geom_richtext(
    fill = NA, label.color = df$color, # remove background and outline
    label.padding = grid::unit(rep(5, 10), "pt") # remove padding
  ) +
  geom_point(color = "black", size = 2) +
  scale_color_identity() +
  xlim(0, 1) + ylim(0, 1)

相关问题