首页 > 解决方案 > 在绘图仪表图中添加悬停文本或文本注释

问题描述

我们可以在plotly仪表图中添加悬停文本或文本注释吗?例如,在我下面的情节中,我想在绿色区域中添加悬停或文本或两者"Uptake first dose%: 19.8"以及灰色区域"Not vaccinated (%):80.2"

library(plotly)

fig <- plot_ly(
  type = "indicator",
  mode = "gauge+number+delta",
  value = 19.8,
  title = list(text = "Uptake first dose %", font = list(size = 24)),
  delta = list(reference = 70, increasing = list(color = "gray")),
  gauge = list(
    axis = list(range = list(NULL, 100), tickwidth = 1, tickcolor = "lightgreen"),
    bar = list(color = "lightgreen"),
    bgcolor = "white",
    borderwidth = 2,
    bordercolor = "gray",
    steps = list(
      list(range = c(0, 50), color = "lightgreen"),
      list(range = c(20, 100), color = "gray")),
    threshold = list(
      line = list(color = "black", width = 4),
      thickness = 0.75,
      value = 70))) 
fig <- fig %>%
  layout(
    margin = list(l=20,r=30),
    paper_bgcolor = "lavender",
    font = list(color = "darkblue", family = "Arial"))

fig

标签: rplotlygauge

解决方案


您可以添加注释,但我找不到在没有注释的情况下获取悬停文本的方法。

fig <- plotly::plot_ly(
  type = "indicator",
  mode = "gauge+number+delta",
  value = 19.8,
  title = list(text = "Uptake first dose %", font = list(size = 24)),
  delta = list(reference = 70, increasing = list(color = "gray")),
  gauge = list(
    axis = list(range = list(NULL, 100), tickwidth = 1, tickcolor = "lightgreen"),
    bar = list(color = "lightgreen"),
    bgcolor = "white",
    borderwidth = 2,
    bordercolor = "gray",
    steps = list(
      list(range = c(0, 50), color = "lightgreen"),
      list(range = c(20, 100), color = "gray")),
    threshold = list(
      line = list(color = "black", width = 4),
      thickness = 0.75,
      value = 70))) 
fig <- fig %>%
  plotly::layout(
    margin = list(l=20,r=30),
    paper_bgcolor = "lavender",
    font = list(color = "darkblue", family = "Arial"),
    annotations = list(x = 0.05, y = 0.3, text = "19.8%",
                       hovertext = "Your Text",
                       showarrow = FALSE))

fig 

add_annotations如果要添加倍数,也可以使用。见https://plotly.com/r/text-and-annotations/


推荐阅读