ggplot2:向散点图添加文本框标签的正确方法

ggplot2: proper way to add a text box label to a scatter plot

提问人:DaniCee 提问时间:11/8/2023 更新时间:11/9/2023 访问量:24

问:

我有以下带有数据的 MWE,我只想在绘图区域顶部制作带有文本框标签的散点图。iris

这是我的输入数据:

data(iris)
set.seed(123)
iris$Group <- sample(LETTERS[1:2], nrow(iris), replace = T)
iris$Highlight <- FALSE
iris$Highlight[iris$Species=="setosa"] <- TRUE
iris$Highlight <- factor(iris$Highlight, levels=c(TRUE, FALSE))
iris$Group[iris$Highlight==FALSE] <- NA
iris$Group <- factor(iris$Group, levels=LETTERS[1:2])
plot_palette <- c("#E41A1C","#377EB8")

我首先尝试制作我想要的情节,没有任何文本框标签:

P <- ggplot2::ggplot(iris, ggplot2::aes(x=Sepal.Length, y=Sepal.Width, color=Group)) +
  ggplot2::geom_point(size=5, alpha=0.5, shape=16) +
  ggplot2::scale_color_manual(values=plot_palette, drop=FALSE,
                              guide=ggplot2::guide_legend(ncol=2, override.aes=list(shape=19, size=8)),
                              na.value="grey75", breaks=LETTERS[1:2]) +
  ggplot2::theme_light() +
  ggplot2::theme(axis.text=ggplot2::element_text(size=15),
                 axis.title=ggplot2::element_text(size=15,face="bold"),
                 legend.text=ggplot2::element_text(size=18),
                 legend.title=ggplot2::element_text(size=15,face="bold"),
                 legend.position="bottom",
                 legend.key.size=grid::unit(0.5,"inch"),
                 plot.margin = grid::unit(c(2,2,0,2), "lines"))
grDevices::png(filename="test1.png", height=600, width=600)
print(P)
grDevices::dev.off()

这完全按照我想要的方式产生了情节:

test1

但是,现在我只想在绘图区域添加一个文本框,这是事情变得混乱的时候。我尝试了,并在多个地方指定:geom_textgeom_label

P <- P + ggplot2::geom_label(x=4.5, y=4, label="this is\nmy label")

...这仍然是我得到的最好的:

test2

为什么标签会显示在图例中?我在这里做错了什么?

如果你能在答案中包括如何修改文本(颜色、大小、使其对齐)和框(背景颜色、线条粗细......),最重要的是,框锚点,那就太棒了。

PS:它实际上不一定是一个盒子,只需文本即可......两者的解决方案将不胜感激。geom_labelgeom_text

谢谢!

R ggplot2 文本 文本框 标签

评论

0赞 Jon Spring 11/8/2023
ggplot2::annotate("label",x=4.5, y=4, label="this is\nmy label")

答:

1赞 Jon Spring 11/8/2023 #1

尝试ggplot2::annotate("label",x=4.5, y=4, label="this is\nmy label")

geom_label与大多数函数(但不是,例如geom_vline)一样,创建一个反映数据中每个观测值的图层。即标签将创建 150 次,每次观察一次,并尊重组到颜色的全局美学映射。此处的标签被添加到图例中,这是另一个不需要的副作用。geom_*

annotate("label", ....)将数据和任何全局美学区分开来。查看 https://ggplot2.tidyverse.org/reference/annotate.html

enter image description here

评论

0赞 DaniCee 11/8/2023
我想我什至不知道,以为是实现这一目标的方法annotategeom_text
0赞 Jon Spring 11/8/2023
我认为你也可以用 / 来做到这一点,用它来给它一个单一的观察和单独的美学映射,但更简单。geom_textgeom_labelggplot2::geom_label(aes(x,y,label="this is\nmy label"), inherit.aes=FALSE, data = data.frame(x = 4.5, y = 4))annotate