【问题标题】:Transparency in X and Y labels - ggplot2, RX 和 Y 标签的透明度 - ggplot2, R
【发布时间】:2019-01-17 18:17:58
【问题描述】:

我正在尝试使 X 和 Y 标签在一定程度上透明。但是,(1)我找不到在 scale_x_continuous() 函数中有效的东西,因为它没有可用的 alpha 函数。有没有其他方法(没有alpha)可以使它们在一定程度上透明?

这是代码:

ggplot(df, aes(x=X, y=Y)) + 
    geom_point(colour="red",size=3) +
  geom_text_repel(label=df$Label, family="sans", fontface="bold", size=3) + 
  scale_x_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 0.5)) + 
  scale_y_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 1),position = "right") +
  annotate("rect", xmin = 0.25, xmax = Inf, ymin = 0.5, ymax = -Inf, fill= "brown2", alpha=0.3) +
  theme_light() +
  geom_hline(yintercept = 0.5,alpha=0.3, color="blue") + geom_vline(xintercept = 0.25,alpha=0.3,color="blue")

【问题讨论】:

  • 你真的需要它们是透明的,或者只是更轻,以匹配你情节其余部分的美感吗?
  • 两者。因为它不仅要与情节的美感相匹配,还必须与幻灯片演示的整个格式相匹配。在其中一些中,我需要它是透明的,而另一些则更轻(这就是我要寻找“alpha”的原因)。

标签: r ggplot2


【解决方案1】:

嗯,它并不漂亮,但这是获得所需内容的一种方法,主要基于 this approach 在情节边界之外进行注释。

标签的scale_x_continuous() 中没有alpha 参数,主题参数中也没有element_text()。您可以为使用 annotate() 制作的文本指定 alpha,并且可以将这些注释放置在绘图区域之外,因此此解决方案使用该方法。

df <- data.frame(X=runif(1), Y=rnorm(1))
ggplot(df, aes(x=X, y=Y)) + 
  geom_point(colour="red",size=3) +
  # geom_text_repel(label=df$Label, family="sans", fontface="bold", size=3) +
  scale_x_continuous(labels = scales::percent_format(accuracy = 1)) + 
  scale_y_continuous(labels = scales::percent_format(accuracy = 1), position = "right") +
  annotate("rect", xmin = 0.25, xmax = Inf, ymin = 0.5, ymax = -Inf, fill= "brown2", alpha=0.3) +
  theme_light() +
  geom_hline(yintercept = 0.5,alpha=0.3, color="blue") + geom_vline(xintercept = 0.25,alpha=0.3,color="blue") +
  theme(axis.title=element_blank(),
     plot.margin = unit(c(5,10,10,5), "mm")) +
  annotate("text", label="X", x=0.25, y=-0.15, alpha=0.5) +
  annotate("text", label="Y", x=0.58, y=0.5, alpha=0.5) +
  coord_cartesian(clip="off", ylim=c(0,1), xlim=c(0,0.5))

几个注意事项:

  • 您需要使用coord_cartesian() 并指定clip="off" 以允许在绘图区域之外进行注释。为了使绘图集中在正确的区域,您还需要指定xlimylim,这意味着您不能在scale_x/y_continuous() 中指定这些参数。 (我已从您的原始代码中删除了这些内容。)
  • 您还需要指定为标签留出足够空间的绘图边距。需要反复试验才能弄清楚这些可能/应该是什么。
  • 还需要一些工作才能确定透明轴标签的位置,因此如果您有多个绘图,这不是一个好方法。

【讨论】:

    猜你喜欢
    • 2021-02-21
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多