Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading