Date format in hover for ggplot2 and plotly

前端 未结 1 1896
日久生厌
日久生厌 2020-12-13 22:55

I have a question about date formats in plotly. I made a time series plot in ggplot2 that I\'m trying to visualize with plotly but a format issue f

相关标签:
1条回答
  • 2020-12-13 23:27

    We can use the "hidden" text aes, to use it in the tooltip:

    ggplot(datosO3.melt) +
        geom_line(aes(x      = fecha, 
                      y      = value, 
                      colour = variable,
                      group  = variable,
                      text   = paste('fecha: ', fecha, '\n',
                                     'variable: ', variable, '\n',
                                     'value: ', value, '\n')
                      )
                  )
    
    ggplotly(tooltip = 'text')
    

    However for anything that's slightly more complicated than default, especially when working with hover tooltips I usually prefer to work directly in plotly:

    plot_ly(datosO3.melt, 
            type      = 'scatter', 
            mode      = 'lines', 
            x         = ~fecha, 
            y         = ~value, 
            color     = ~variable,
            text      = ~paste('fecha: ', fecha, '\n',
                               'variable: ', variable, '\n',
                               'value: ', value, '\n'),
            hoverinfo = 'text'
            )
    

    To use a custom date format, other the print.Date default, just substitute fecha with the format you prefer, e.g:

    plot_ly(datosO3.melt, 
            type = 'scatter', 
            mode = 'lines', 
            x = ~fecha, 
            y = ~value, 
            color = ~variable,
            text = ~paste('fecha: ', format(fecha, '%Y-%m-%d %H:%M'), '\n',
                               'variable: ', variable, '\n',
                               'value: ', value, '\n'),
            hoverinfo = 'text'
            )
    
    0 讨论(0)
提交回复
热议问题