rabbert_klein rabbert_klein - 1 month ago 14
R Question

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?

Answer

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