Search code examples
rggplot2labelgeom-text

labeling geom_point in ggplot R


I am trying to recreate a plot and I have several lines in there, which are in the legend but next to this the plot also has some points. How could I put labels in this plot at the points. Note that the points are not in the data frame. My code looks like this now:

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

Solution

  • To label the points you can add geom_text layers with point coordinates and the label.

    Using mtcars as example data set try this:

    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)