How to pass in variable in the hover label using plotly in R

Viewed 8
mydat2 <- data.frame(subject = c("math", "english", "chemistry"), score = c(80, 50, 65), class = c("A", "B", "A"), count = c(50, 60, 70))
> mydat2
    subject score class count
1      math    80     A    50
2   english    50     B    60
3 chemistry    65     A    70

I have the above data. And I plot the following:

library(plotly)
plot_ly(data = mydat2,
        x = ~score,
        y = ~count,
        color = ~class,
        hoverinfo = 'text',
        text = ~subject,
        hovertemplate = paste(
          "<b>%{text}</b><br><br>",
          "%{yaxis.title.text}: %{y:,.0f}<br>",
          "%{xaxis.title.text}: %{x:,.0f}<br>",
          "Class: %{color:,.0f}",
          "<extra></extra>"
        ))

I want the hover label to also include what the class is. However, I cannot seem to get the right hover label. It's showing up as Class: %{color:.,.0f}

enter image description here

1 Answers

One needs to use the "customdata" option in the hover text definition.

mydat2 <- data.frame(subject = c("math", "english", "chemistry"), score = c(80, 50, 65), class = c("A", "B", "A"), count = c(50, 60, 70))

library(plotly)
plot_ly(data = mydat2,
        x = ~score,
        y = ~count,
        color = ~class,
        customdata= ~class,
        hoverinfo = 'text',
        text = ~subject,
        hovertemplate = paste(
           "<b>%{text}</b><br><br>",
           "%{yaxis.title.text}: %{y:,.0f}<br>",
           "%{xaxis.title.text}: %{x:,.0f}<br>",
           "Class: %{customdata}",
           "<extra></extra>"
        ))
Related