Home > database >  How to add value labels in ggplot time series
How to add value labels in ggplot time series

Time:08-29

How can I add the labels with the respective values in ggplot time series graph ?

I tried, but with no success...

library(ggplot2)
library(ggrepel)
library(dplyr)
library(plotly)

set.seed(1234)

df <- data.frame(
  dates = c(
    "2022-01-01",
    "2022-01-02",
    "2022-01-03",
    "2022-01-04",
    "2022-01-05",
    "2022-01-06",
    "2022-01-07",
    "2022-01-08",
    "2022-01-09",
    "2022-01-10",
    "2022-01-11",
    "2022-01-12",
    "2022-01-13",
    "2022-01-14",
    "2022-01-15",
    "2022-01-16",
    "2022-01-17",
    "2022-01-18",
    "2022-01-19",
    "2022-01-20"
  ),
  yhat  = rnorm(20, 0, 1),
  realv = rnorm(20, 0, 1)
) %>%
  mutate(
    dates = as.Date(dates)
  )

By using plotly, I tried...

ggplotly(
  ggplot(df, aes(x = dates))   
    geom_line(aes(y = yhat), color = "red")  
    geom_line(aes(y = realv), color = "black")   
    
    geom_text_repel(data = df, aes(dates, yhat, label = realv)) 

)

I tried to add labels using geom_text(aes(label = as.character(yhat_final)), size = 7) but it didn´t worked too..

CodePudding user response:

As per Warning message geom_text_repel is not yet implemented in plotly.

Warning message: In geom2trace.default(dots[[1L]][[1L]], dots[[2L]][[1L]], dots[[3L]][[1L]]) : geom_GeomTextRepel() has yet to be implemented in plotly. If you'd like to see this geom implemented, Please open an issue with your example code at https://github.com/ropensci/plotly/issues

You can work around using geom_text and playing on the y value:

ggplotly( ggplot(df, aes(x = dates))   
geom_line(aes(y = yhat), color = "red")  
geom_line(aes(y = realv), color = "black")   
geom_text(data = df, aes(dates, yhat   0.2, label = round(realv, digits = 1))))
  • Related