Search code examples
rggplot2labelgeom-text

How to add customized labels to ggplot?


I am attempting to add labels from another column (year), to my ggplot graph, but its giving me the following error:

Error: geom_text_repel requires the following missing aesthetics: label

My data: thirdgraph2

year      pdor         juni
2016      1991-06-26   13305.0
2019      1991-06-16   13598.0
2017      1991-06-17   13944.5
2018      1991-06-17   15653.5
2015      1991-07-08   17143.0

Here is the code I used:

  ggplot(thirdgraph2, aes(juni, pdor, label=rownames(thirdgraph2$year))) + 
         geom_point() + 
         theme_bw() + 
         labs(y="Calculated date of reproduction", 
         x="Accumulated GDD until 17th June") + 
         geom_text_repel()

So I like the labels to be the year instead of the default 1-5. Does anybody know a way?


Solution

  • Does this work?:

    library(tibble)
    library(ggplot2)
    library(ggrepel)
    library(dplyr)
    
    
    ggplot(thirdgraph2, aes(juni, pdor, label=year)) + 
      geom_point() + 
      theme_bw() + 
      labs(y="Calculated date of reproduction", 
           x="Accumulated GDD until 17th June") + 
      geom_text_repel()
    

    Created on 2021-07-08 by the reprex package (v2.0.0)

    data

    thirdgraph2 <- tribble(
      ~"year",      ~"pdor",      ~"juni",
    2016,      "1991-06-26", 13305.0,
    2019,      "1991-06-16", 13598.0,
    2017,      "1991-06-17", 13944.5,
    2018,      "1991-06-17", 15653.5,
    2015,      "1991-07-08", 17143.0)
    
    #assuming you want the dates as dates: 
    
    thirdgraph2 <- 
      thirdgraph2 %>% 
      mutate(pdor = as.Date(pdor, format = "%Y-%m-%d"))