【问题标题】:labeling geom_point in ggplot R在ggplot R中标记geom_point
【发布时间】:2026-01-31 14:15:02
【问题描述】:

我正在尝试重新创建一个情节,其中有几行,它们在图例中,但在这个情节旁边也有一些要点。我怎么能在这个图中的点上放置标签。请注意,这些点不在数据框中。我的代码现在看起来像这样:

ggplot(df, aes(x=tau_3)) + 
  geom_line(aes(y= a1, color = "blue")) + 
  geom_line(aes(y= a2, color = "green"))+ 
  xlim(0,0.6) + 
  ylim(0,0.4) +  
  geom_point(aes(0,0), size =5 , shape = "square")  + 
  geom_point(aes(0,1/6), size =5 , shape = "circle") +   
  geom_point(aes(0,0.1226), size =5 , shape = "triangle")  +  
  scale_color_discrete(name = "Legend", labels = c("GLO", "GEV"))

【问题讨论】:

  • 你有一些数据要处理吗?

标签: r ggplot2 label geom-text


【解决方案1】:

要标记点,您可以添加带有点坐标和标签的geom_text 层。

使用mtcars 作为示例数据集试试这个:

library(ggplot2)

ggplot() +
  geom_point(data = mtcars, aes(hp, mpg, color = factor(cyl))) +
  geom_point(aes(200, 25), color = "black") +
  geom_point(aes(100, 12), color = "purple") +
  geom_text(aes(200, 25), label = "I'm a black point", color = "black", nudge_y = .5) +
  geom_text(aes(100, 12), label = "I'm a purple point", color = "purple", nudge_y = -.5)

【讨论】:

  • 谢谢你这很好用!一个问题如何更改标签的大小?
  • 嗨@Elliot。不客气。您可以使用 size 参数调整字体大小。请注意,大小以mm 为单位。有关样式和调整位置的更多信息,请参阅ggplot2.tidyverse.org/articles/ggplot2-specs.html#text-1
  • 我需要把 size 参数放在 geom_text 的 aes() 中吗?因为我没有看到任何差异。
  • 对不起。不。将size 放在aes 之外。这就是我们说“使用 xxx 作为参数”时的意思。 (;
【解决方案2】:

解决问题的一种方法是将点的坐标和形状放在辅助数据帧df_points 中,并在geom_pointgeom_text 中使用。

至于线条,重塑数据from wide to long format 并调用geom_line 就足够了。设置参数inherit.aes = FALSE,在geom_point的情况下也设置show.legend = FALSE

library(ggplot2)
library(dplyr)
library(tidyr)

df_points <- data.frame(x = rep(0, 3), 
                        y = c(0, 1/6, 0.126),
                        shape = factor(c("square", "circle", "triangle"), 
                                       levels = c("square", "circle", "triangle")))

df %>%
  pivot_longer(
    cols = starts_with('a'),
    names_to = 'y',
    values_to = 'a'
  ) %>%
  ggplot(aes(tau_3, a, color = y)) +
  geom_line() +
  geom_point(data = df_points, 
             mapping = aes(x, y, shape = shape), 
             size = 5, 
             show.legend = FALSE,
             inherit.aes = FALSE) +
  geom_text(data = df_points, 
            mapping = aes(x, y, label = shape), 
            vjust = -1.5, hjust = 0,
            inherit.aes = FALSE) +
  xlim(0,0.6) + 
  ylim(0,0.4) +  
  scale_color_manual(name = "Legend", 
                     values = c("blue", "green"),
                     labels = c("GLO", "GEV")) +
  scale_shape_manual(values = c("square", "circle", "triangle"))

测试数据

set.seed(2020)
n <- 20
tau_3 <- runif(n, 0, 0.6)
a1 <- runif(n, 0, 0.4)
a2 <- runif(n, 0, 0.4)
df <- data.frame(tau_3, a1, a2)

【讨论】: