es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Agregue anotaciones a series de tiempo con highcharter.

Quiero agregar anotaciones con Highcharter. Podría hacerlo con gráficos de dispersión “clásicos”:

library(highcharter)
df <- data.frame(
  x = 1:10,
  y = 1:10
)
hchart(df, "line", hcaes(x = x, y = y)) %>%
  hc_annotations(
    list(
      labels = lapply(1:nrow(df),function(i){
        list(point = list(x = df$x[i],y = df$y[i],xAxis = 0,yAxis = 0))
      })
    )
  )

El problema es que me gustaría hacerlo cuando mi eje X es una fecha y de alguna manera no puedo hacer que funcione:

df <- data.frame(
  x = seq(as.Date("2021-01-01"), as.Date("2021-01-10"), by = "days"),
  y = 1:10
)
hchart(df, "line", hcaes(x = x, y = y)) %>%
  hc_annotations(
    list(
      labels = lapply(1:nrow(df),function(i){
        list(point = list(x = df$x[i],y = df$y[i],xAxis = 0,yAxis = 0))
      })
    )
  )
Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para agregar anotaciones con Highcharter cuando el eje X es una fecha, debes establecer el tipo de xAxis en “datetime” y convertir las fechas a milisegundos utilizando la función as.numeric(). Aquí tienes el código actualizado:

    “`{r}
    library(highcharter)

    df <- data.frame(
    x = seq(as.Date(“2021-01-01”), as.Date(“2021-01-10”), by = “days”),
    y = 1:10
    )

    hchart(df, “line”, hcaes(x = x, y = y)) %>%
    hc_xAxis(type = “datetime”) %>% # establecer el tipo de xAxis como datetime
    hc_annotations(
    list(
    labels = lapply(1:nrow(df), function(i) {
    list(point = list(x = as.numeric(df$x[i]), y = df$y[i], xAxis = 0, yAxis = 0)) # convertir las fechas a milisegundos
    })
    )
    )
    “`

    Esto debería agregar correctamente las anotaciones al gráfico con el eje X como una fecha.

Comments are closed.