Search code examples
rggplot2plotly

Is there a way to add more information when hovering over a Plotly graph?


I made a graph, which you can see below. When hovering over a Plotly graph, you can see helpful info present in the graph like the Store Num etc. Is there a way to add to this label, so when someone hovers they can also see the branding ? As in, not just Store Num? Thanks!

Store Num mean_sales mean_outreach branding
1 200 1200 1
2 4200 1403 2
plotly::ggplotly(ggplot(data, aes(x= mean_sales, y= mean_outreach, label= `Store Num`))+
                   geom_point() +geom_text(aes(label= `Store Num`),hjust=20, vjust=20) +
                   ggtitle("Examining Marketing Campaign Outreach"))

When I try writing two labels, then the label itself will change but the value for both Store Num and branding will be the store number. As in both labels I want aren't showing correctly.

plotly::ggplotly(ggplot(data, aes(x= mean_sales, y= mean_outreach, label= `Store Num`))+
                   geom_point() +geom_text(aes(label= branding),hjust=20, vjust=20) +
                   ggtitle("Examining Marketing Campaign Outreach"))

Solution

  • You could achieve your desired result with a customized tooltip via the text aesthetic (see https://plotly-r.com/controlling-tooltips.html#tooltip-text-ggplotly):

    library(plotly)
    
    ggplot(data, aes(
      x = mean_sales, y = mean_outreach, label = Store.Num,
      text = paste0(
        "mean_sales: ", mean_sales, "<br>",
        "mean_outreach: ", mean_outreach, "<br>",
        "Store Num: ", Store.Num, "<br>",
        "branding: ", branding
      )
    )) +
      geom_point() +
      geom_text(hjust = 0, vjust = 0) +
      ggtitle("Examining Marketing Campaign Outreach")
    
    ggplotly(tooltip = "text")
    

    Or if you only want to add information to the defaults you could do:

    ggplot(data, aes(
      x = mean_sales, y = mean_outreach, label = Store.Num,
      text = paste0(
        "branding: ", branding
      )
    )) +
      geom_point() +
      geom_text(hjust = 0, vjust = 0) +
      ggtitle("Examining Marketing Campaign Outreach")
    
    ggplotly(tooltip = "all")
    

    enter image description here