rabbert_klein
rabbert_klein

Reputation: 383

How to add line breaks to plotly hover labels

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?

Upvotes: 34

Views: 21921

Answers (2)

Peter Painter
Peter Painter

Reputation: 31

I just noticed that Plotly ASSumes that the 2nd line created that way is a percentage value. If the line starts with a number value that can be parsed, it will take that number, format it, add a percentage sign and overwrite the second line. This happens even if the hoverinfo does not specify 'percent'. At least it happens this way with the 'text' labels - I didn't try with 'hovertext'

Solution is to precede the value with '&nbsp;'

Upvotes: 1

Martin Schmelzer
Martin Schmelzer

Reputation: 23889

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)...

Upvotes: 67

Related Questions