Search code examples
cssrr-plotlyggplotly

How to colour part of ggplotly/plotly hover text a different colour in R


I would like to colour part of the hover text another colour in a ggplotly object. It is easy to bold and italicise but it doesn't seem to be the same ease for font colour. I thought the code below should work

Example with the Iris data set:

library(plotly)
library(ggplot2)
library(htmltools)
library(dplyr)

iris_in <- iris %>%
  mutate(mytext = paste0("<b>Sepal length:</b> ", Sepal.Length, "\n",
                       p(text = "Sepal width: ", style="color:red"), Sepal.Width))
  p <- ggplot() +
  geom_point(data = iris_in, aes(x = Sepal.Length, y = Sepal.Width, color = Species, text = mytext))

p <- ggplotly(p, tooltip = "mytext")

p

I can bold Sepal Length but I can't change the Sepal Width title to red. Help would be greatly appreciated! Plot as is from code above


Solution

  • You could achieve your desired result by using a span instead of a p tag:

    library(plotly)
    library(ggplot2)
    library(dplyr)
    
    iris_in <- iris %>%
      mutate(mytext = paste0("<b>Sepal length:</b> ", Sepal.Length, "\n",
                             "<span style='color:red'>Sepal width: </span>", Sepal.Width))
    p <- ggplot() +
      geom_point(data = iris_in, aes(x = Sepal.Length, y = Sepal.Width, color = Species, text = mytext))
    
    p <- ggplotly(p, tooltip = "mytext")
    
    p
    

    enter image description here