在 ggplot R 中标记 geom_point

labeling geom_point in ggplot R

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

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

要标记点,您可以使用点坐标和标签添加 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)

解决问题的方法是将点的坐标和形状放在辅助data.frame 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)