【问题标题】:R shiny: Change "height" attribute of rectangle in gvisTimelineR闪亮:更改gvisTimeline中矩形的“高度”属性
【发布时间】:2016-10-22 05:10:23
【问题描述】:

我在 R Shiny-App 中使用 gvisTimeline

library(shiny)
library(googleVis)

ui <-fluidRow(
  tags$head(
    tags$script(src="https://d3js.org/d3.v3.min.js", {{ suppressDependencies("d3") }})
  ),
  htmlOutput("timeline")
  )

server <- function(input, output) {

dat <- data.frame(Term=c("1","2","3"),
                  President=c("Whashington", "Adams", "Jefferson"),
                  start=as.Date(x=c("1789-03-29", "1797-02-03", "1801-02-03")),
                  end=as.Date(x=c("1797-02-03", "1801-02-03", "1809-02-03")))

output$timeline <-renderGvis({
                    gvisTimeline(data=dat[,-1], rowlabel="President",
                    start="start", end="end")
          })
    }

shinyApp(ui, server)

我想改变中间矩形的高度。我通过在 JavaScript 控制台中选择适当的 svg 元素来实现这一点:

d3.select('svg:nth-child(1) g:nth-child(5) rect:nth-child(2)')
.attr('height', 42)
.attr('y', 40);

如何将此代码集成到 Shiny-App 中,以便从一开始就获得所需高度和 y 坐标的这个矩形?感谢您的帮助!

【问题讨论】:

    标签: javascript r d3.js svg shiny


    【解决方案1】:

    这里的问题是时间线是在页面加载几毫秒后从 Google 服务器传输的。您需要在此传输发生后执行您的 JavaScript 代码,即页面初始化后 50 或 500 毫秒。以下代码将每 50 毫秒执行一次,虽然有效,但远非完美。

    1. 在 UI 中,您需要一个虚拟输出 "uiOutput("timelineAdjustment")":

      uiOutput("timelineAdjustment")
      
    2. 在Server中,需要定义如下:

      autoInvalidate50msec <- reactiveTimer(50, session)
      output$timelineAdjustment <- renderUI({
         autoInvalidate50msec()
         HTML("<script type='text/javascript'>d3.select('#timeline svg:nth-child(1) g:nth-child(5) rect:nth-child(2)').attr('height', 42).attr('y', 40);</script>")
      })
      

    或者,如果您在页面加载后只执行一次(1000ms),则等效定义:

    output$timelineAdjustment <- renderUI({
        HTML("<script type='text/javascript'>setTimeout(function() { d3.select('#timeline svg:nth-child(1) g:nth-child(5) rect:nth-child(11)').attr('height', 41).attr('y', 41); },1000);</script>")
    })
    

    如果有更好的方法来实现这一点,我很高兴听到!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 2019-10-12
      • 2020-05-08
      • 2019-05-21
      • 1970-01-01
      • 2021-11-11
      • 2015-11-19
      相关资源
      最近更新 更多