Date format in hover for ggplot2 and plotly

被刻印的时光 ゝ 提交于 2019-11-28 19:58:01

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'
        )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!