gpt4 book ai didi

r - 如何避免在文本注释上绘制 geom_line ?

转载 作者:行者123 更新时间:2023-12-02 03:41:24 25 4
gpt4 key购买 nike

我有一个图,其中每个点都有点、线和注释。问题是线条最终会穿过注释文本,我想找到一个解决方案来避免这种情况,例如如何使注释位于“顶部”?

我的伪 ggplot 就像:

# some df
ggplot(df,aes(x=x,y=y)) + geom_line() + geom_point() +
annotate('text', ...)

请注意,如果我交换geom_linegeom_point的顺序,该线将绘制在该点的顶部(当然,当颜色不是黑色或有透明度时) 。但是,该线将直接穿过注释文本。

我该如何解决这个问题?到目前为止,我选择不包含线条,但会很好。

最佳答案

也许最好的选择是使用geom_label,它将在标签文本下方放置一个白色背景,覆盖该线(如果放置在geom_line之后)。这样做的优点是,白色背景的大小将被调整为恰好空白将穿过标签的线条部分。

如果您只有一个标签,如下面的 annotate 代码所示,则可以单独使用 geom_label。但是,如果您有多个可能重叠的标签,则需要两次调用,一次调用 geom_labelcolour="white" 来生成空白“标签”覆盖该线,然后调用geom_text来获取标签本身。这是因为单独使用 geom_label 时,标签背景会重叠并遮盖重叠标签的文本。

library(tidyverse)
theme_set(theme_classic())

ggplot(mtcars[1:20,], aes(wt, mpg)) +
geom_line() +
geom_label(aes(label=round(mpg,2)), colour="white", label.padding=unit(0.05,"lines"),
size=3) +
geom_text(aes(label=round(mpg,2)), size=3) +
annotate("label", 2.25, 27, label="Label", colour="red", label.size=0)

在上面的代码中,label.size=0 消除了标签周围的边框。

enter image description here

另一种选择是在注释下方、行上方放置一个方形白点标记:

ggplot(mtcars[1:20,], aes(wt, mpg)) + 
geom_line() +
geom_point(shape=15, colour="white", size=6) +
geom_text(aes(label=round(mpg,2)), size=3) +
annotate("point", 2.25, 27, pch=15, size=7, colour="white") +
annotate("text", 2.25, 27, label="Label", colour="red")

enter image description here

您还可以使线条不那么突出。下面它们只是引导视线,但不会过多干扰:

ggplot(mtcars[1:20,], aes(wt, mpg)) + 
geom_line(linetype="11", colour="grey30", size=0.25) +
geom_text(aes(label=round(mpg,2)), size=3) +
annotate("text", 2.25, 27, label="Label", colour="red")

enter image description here

关于r - 如何避免在文本注释上绘制 geom_line ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48510969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com