34

Is there a way to get plotly to display the hover text on multiple lines/get it to recognize special characters line '\n' in the text?

A dummy version of what I'm looking to do is:

data <- data.frame(cbind(rnorm(10, 8), rnorm(10, 2)))
names(data)<-c("thing1", "thing2")

data$hovertext <- paste("here's a coordinate: ",
                         round(data$thing1,1), sep = "\n")


p <- plot_ly(data, type = 'scatter', x = thing1, y = thing2, 
             text = hovertext, hoverinfo = 'text', mode = "markers")

Which of course just ignores the separator and prints all on one line. Can I trick plotly/R into recognizing that line break?

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
rabbert_klein
  • 383
  • 1
  • 3
  • 5

1 Answers1

64

Just use the HTML tag <br>:

library(plotly)
data <- data.frame(cbind(rnorm(10, 8), rnorm(10, 2)))
names(data) <- c("thing1", "thing2")

data$hovertext <- paste("here's a coordinate:",
                     round(data$thing1,1), sep = "<br>")


p <- plot_ly(data, type = 'scatter', x = ~thing1, y = ~thing2, 
         text = ~hovertext, hoverinfo = 'text', mode = "markers")

Additionally, you could use HTML tags to change the font styles as well (and much more)...

rawr
  • 20,481
  • 4
  • 44
  • 78
Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
  • 13
    Just want to add: make sure to use `
    ` and *not* `
    ` – the latter will not work.
    – adilapapaya Oct 17 '16 at 15:41
  • 5
    `
    `, `
    `, and `
    ` are three different tags; the first two work, the third will not
    – rawr Apr 02 '17 at 16:54
  • @Martin: can you please take a look at my question? https://stackoverflow.com/questions/68242473/r-adding-a-tool-tip-to-interactive-plot-plotly Thanks! – stats_noob Jul 05 '21 at 03:29