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

问题描述 投票:0回答:1

我有以下带有

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

这是我的输入数据:

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()

这会按照我想要的方式产生情节:

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

geom_text
geom_label

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

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

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

如果您可以在答案中包含如何修改文本(颜色、大小、使其合理)和框(背景颜色、线条粗细...),最重要的是框锚点,那就太棒了.

PS:它实际上不必是一个盒子,只需文本即可...同时具有

geom_label
geom_text
的解决方案将不胜感激。

谢谢!

r ggplot2 text textbox label
1个回答
1
投票

尝试

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

与大多数

geom_label

 函数(但不是 geom_vline)一样,
geom_*
会创建一个反映数据中每个观测值的图层。即该标签将被创建 150 次,每次观察一次,并尊重群体到颜色的全球审美映射。这里的标签被添加到图例中,这是另一个不需要的副作用。

annotate("label", ....)
与数据和任何全局美学隔离开来。请参阅https://ggplot2.tidyverse.org/reference/annotate.html

© www.soinside.com 2019 - 2024. All rights reserved.