Search code examples
rplotly

How to specify additional variable in R Plotly's hovertemplate?


I'm using R and am trying to add a variable other than x, y, or z to my Plotly hovertemplate.

In the example code below, I'd like to add a variable, weight, to the hover, but haven't found a way to do so (the current code just shows the string "{weight}" rather than the values of the weight variable.

I've seen a solution for this in Python, but not R. Any advice is greatly appreciated. Thank you.

library(plotly)
library(tidyverse) 

my_tibble <- tibble(mins = runif(10,10,30),
                     week = 1:10,
                     exercise = c("a", "b", "b", "b", "a", "a", "b", "b", "b", "a"),
                     weight = runif(10,150,160))

example_hex <- c('#70AD47', '#404040', '#CAE1F1', '#24608B')

plot_ly(
  data = my_tibble,
  type = 'bar',
  x = ~week,
  y = ~mins,
  color = ~exercise,
  colors = example_hex,
  hovertemplate = paste('<b>Week</b>: %{x}',
                                "%{weight}",
                                '<extra></extra>')
)

Solution

  • You can assign the variable to the text argument and include it the same way as x and y.

    plot_ly(
      data = my_tibble,
      type = 'bar',
      x = ~week,
      y = ~mins,
      color = ~exercise,
      colors = example_hex,
      text = ~weight,   # assign weight to 'text'
      hovertemplate = paste('<b>Week</b>: %{x}',
                            "%{text}",  # text = weight
                            '<extra></extra>')
    )
    

    found here: https://plotly.com/r/hover-text-and-formatting/