如何在 R 中为 ggplotly/plotly 悬停文本的一部分着色不同的颜色

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

我想在 ggplotly 中为悬停文本的一部分着色另一种颜色 object。粗体和斜体很容易,但字体颜色似乎并不容易。我认为下面的代码应该可以工作

Iris 数据集示例:

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

我可以将萼片长度加粗,但无法将萼片宽度标题更改为红色。帮助将不胜感激!

您可以使用 span 而不是 p 标签来达到您想要的结果:

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