代码之家  ›  专栏  ›  技术社区  ›  bbroxler

如何在R Plotly的hovertemplate中指定其他变量?

  •  0
  • bbroxler  · 技术社区  · 2 年前

    我正在使用R,并试图将x、y或z以外的变量添加到我的Plotly hovertemplate中。

    在下面的示例代码中,我想向悬停添加一个变量weight,但没有找到这样做的方法(当前代码只显示字符串“{weight}”,而不是weight变量的值)。

    我在Python中看到了一个解决方案,但不是R。非常感谢您的任何建议。非常感谢。

    library(plotly)
    library(tidyverse) 
    
    my_tibble <- tibble(mins = runif(10,10,30),
                         week = 1:10,
                         exercise = c("a", "b", "b", "b", "a", "a", "b", "b", "b", "a"),
                         weight = runif(10,150,160))
    
    example_hex <- c('#70AD47', '#404040', '#CAE1F1', '#24608B')
    
    plot_ly(
      data = my_tibble,
      type = 'bar',
      x = ~week,
      y = ~mins,
      color = ~exercise,
      colors = example_hex,
      hovertemplate = paste('<b>Week</b>: %{x}',
                                    "%{weight}",
                                    '<extra></extra>')
    )
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   TTS    2 年前

    您可以将变量分配给 text 参数,并以与 x y

    plot_ly(
      data = my_tibble,
      type = 'bar',
      x = ~week,
      y = ~mins,
      color = ~exercise,
      colors = example_hex,
      text = ~weight,   # assign weight to 'text'
      hovertemplate = paste('<b>Week</b>: %{x}',
                            "%{text}",  # text = weight
                            '<extra></extra>')
    )
    

    在此处找到: https://plotly.com/r/hover-text-and-formatting/