Hover Text and Formatting in R

How to use hover text and formatting in R with Plotly.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Sign up for early access now.

Add Hover Text

library(plotly)

fig <- plot_ly(type = 'scatter', mode = 'markers') 
fig <- fig %>%
  add_trace(
    x = c(1:5), 
    y = rnorm(5, mean = 5),
    text = c("Text A", "Text B", "Text C", "Text D", "Text E"),
    hoverinfo = 'text',
    marker = list(color='green'),
    showlegend = F
  )

fig

Unified hovermode

If you set the hovermode attribute of your figure's layout to x unified or y unified), a single hover label will appear, describing one point per trace, for points at the same x (or y) value as the cursor.

If multiple points in a given trace exist at the same coordinate, only one will get an entry in the hover label. In the line plot below we have forced markers to appear, to make it clearer what can be hovered over:

library(plotly)

trace_0 <- rnorm(100, mean = 5)
trace_1 <- rnorm(100, mean = 0)
trace_2 <- rnorm(100, mean = -5)
x <- c(1:100)

data <- data.frame(x, trace_0, trace_1, trace_2)

fig <- plot_ly(data, x = ~x, y = ~trace_0, name = 'trace 0', type = 'scatter', mode = 'lines') 
fig <- fig %>% add_trace(y = ~trace_1, name = 'trace 1', mode = 'lines+markers') 
fig <- fig %>% add_trace(y = ~trace_2, name = 'trace 2', mode = 'markers')
fig <- fig %>%
  layout(hovermode = "x unified")
fig
020406080100−6−4−202468
trace 0trace 1trace 2xtrace_0

Format Hover Text

library(plotly)

fig <- plot_ly(type = 'scatter', mode = 'markers') 
fig <- fig %>%
  add_trace(
    x = c(1:100), 
    y = rnorm(100, mean = 5), 
    marker = list(color='green'),
    hoverinfo = 'y',
    showlegend = F
  ) 
fig <- fig %>%
  layout(
    title = list(text="Set hover text formatting<br><a href= https://github.com/d3/d3-time-format/blob/master/README.md#locale_format>https://github.com/d3/d3-time-format/blob/master/README.md#locale_format</a>",
      size = 10),
    xaxis = list(zeroline = F),
    yaxis = list(hoverformat = '.2f'))

fig

Customize Tooltip Text with a Hovertemplate

To customize the tooltip on your graph you can use hovertemplate, which is a template string used for rendering the information that appear on hoverbox. This template string can include variables in %{variable} format, numbers in d3-format's syntax, and date in d3-time-fomrat's syntax. Hovertemplate customize the tooltip text vs. texttemplate which customizes the text that appears on your chart.
Set the horizontal alignment of the text within tooltip with hoverlabel.align.

library(plotly)

fig <- plot_ly() 
fig <- fig %>%
  add_trace(
    type = 'scatter',
    mode = 'lines+markers',
    x = c(1,2,3,4,5),
    y = c(2.02825,1.63728,6.83839,4.8485,4.73463),
    text = c("Text A", "Text B", "Text C", "Text D", "Text E"),
    hovertemplate = paste('<i>Price</i>: $%{y:.2f}',
                        '<br><b>X</b>: %{x}<br>',
                        '<b>%{text}</b>'),
    showlegend = FALSE
  ) 
fig <- fig %>%
  add_trace(
    type = 'scatter',
    mode = 'lines+markers',
    x = c(1,2,3,4,5),
    y = c(3.02825,2.63728,4.83839,3.8485,1.73463),
    hovertemplate = 'Price: %{y:$.2f}<extra></extra>',
    showlegend = FALSE
  )

fig
library(plotly)
fig <- plot_ly() 
fig <- fig %>%
  add_trace(
    type = "pie",
    name = "",
    values = c(2, 1, 3, 2.5),
    labels = c("R", "Python", "Java Script", "Matlab"),
    text = c("textA", "TextB", "TextC", "TextD"),
    hovertemplate = "%{label}: <br>Popularity: %{percent} </br> %{text}")


fig
TextC35.3%TextD29.4%textA23.5%TextB11.8%
Java ScriptMatlabRPython

Advanced Hovertemplate

library(plotly)

df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/job-automation-probability.csv')

fig <- df %>%
  plot_ly(
    type = 'scatter',
    mode = 'markers',
    x = ~prob,
    y = ~Average.annual.wage,
    marker = list(size = ~numbEmployed, sizeref = 4000, sizemode = 'area'),
    color = ~education,
    text = ~short.occupation,
    hovertemplate = paste(
      "<b>%{text}</b><br><br>",
      "%{yaxis.title.text}: %{y:$,.0f}<br>",
      "%{xaxis.title.text}: %{x:.0%}<br>",
      "Number Employed: %{marker.size:,}",
      "<extra></extra>"
      )
    ) 
fig <- fig %>%
  layout(legend = list(orientation = 'h', y = -0.3))

fig
00.20.40.60.81050k100k150k200k
Associate's degreeBachelor's degreeDoctoral or professional degreeHigh school diploma or equivalentMaster's degreeNo formal educational credentialPostsecondary nondegree awardSome college, no degreeprobAverage.annual.wage

Reference

See https://plotly.com/r/reference/ for more information and options!

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)