【问题标题】:Tooltip next to axis titles轴标题旁边的工具提示
【发布时间】:2021-09-27 05:25:57
【问题描述】:

目前,我正在使用rshiny 制作仪表板,并在其中绘制图表。但是,我想知道是否有办法在绘图中的 X 和 Y 轴 标题 旁边添加工具提示?

具体来说,是轴标题旁边的问号或(等价的),最终用户可以单击或悬停在此处查看关于轴真正含义的更详细说明。

类似这样的东西(虽然不起作用):

layout(showlegend = FALSE,
       separators = ',.',
       xaxis = list(title = "Age", tooltip = "The age of every female above 50 years in the Unites States of America"))

【问题讨论】:

标签: r shiny plotly dashboard shinydashboard


【解决方案1】:

很遗憾,我不知道有什么包可以做到这一点,但您可以使用带有 HTML 和 JS 的 plotly 将容器绑定到包含工具提示的标题:

编辑:添加了 yaxis(这往往更难一些)

df <- data.frame(a = 1:3,
                 b = 4:6)

jscode <- "
$(document).ready(function() {
    $(\"[data-toggle='tooltip']\").tooltip({container: 'body'}); 
});
"

csscode <- HTML('
    .plot-container {
        position: relative;
    }
    .xaxis-container {
        height: 20px;
        position:absolute;
        bottom: 0;
        left: 40px;
        background: #fff;
        opacity: 0.5;
    }
    .yaxis-container {
        width: 20px;
        position:absolute;
        bottom: 0;
        left: 5px;
        background: #fff;
        opacity: 0.5;
    }
    .xaxis-tooltip {
        width: 30px;
        height: 20px;
        background: #000;
        margin:auto;
    }
    .yaxis-tooltip {
        width: 20px;
        height: 30px;
        background: #000;
        margin:auto;
    }
')

library(shiny)
library(plotly)

ui <- fluidPage(
  tags$head(
    tags$script(jscode),
    tags$style(csscode)
  ),
  div(class = 'plot-container',
      plotlyOutput("plot"),
      div(
        class = "xaxis-container",
        div(class = "xaxis-tooltip", "data-toggle" = "tooltip", "title" = "x")
      ),
      div(
        class = "yaxis-container",
        div(class = "yaxis-tooltip", "data-toggle" = "tooltip", "title" = "y")
      )
  )
)

server = function(input, output) {
  output$plot <- renderPlotly({
    plot_ly() %>%
      add_trace(
        data = df,
        x =  ~ a,
        y =  ~ b,
        type = "scatter"
      ) %>%
      htmlwidgets::onRender("
          function(el, x) {
             var width = $('.draglayer')[0].getBoundingClientRect().width;
             var height = 0.5*$('.yaxis-tooltip')[0].getBoundingClientRect().height+$('.plot-container')[0].getBoundingClientRect().height-0.5*$('.draglayer')[0].getBoundingClientRect().height;
             $('.xaxis-container').css('width', width);
             $('.yaxis-container').css('height', height);
          }
        ")
  })
}

shinyApp(ui, server)

看起来像这样:

您可以将不透明度更改为 0 以使容器不可见,这只是概念验证。

【讨论】:

    猜你喜欢
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多