草庐IT

javascript - 将 javascript (d3.js) 绑定(bind)到 shiny

coder 2023-07-05 原文

首先,我对 javascript 及其库 d3.js 相当陌生,但我熟悉 R。使用 Shiny 创建仪表板既有趣又简单(感谢 stackoverflow)。现在我想通过将 d3 元素连接到它来扩展它。

我正在寻找有关如何实际将 javascript 绑定(bind)到 Shiny(R 仪表板)并解释实际情况的信息源。

背景: 我在 w3schools 上完成了关于 js 和 jquery 的教程,并使用 Scott Murray 的书(网络交互式数据可视化)学习了(一点)关于 d3 的知识。我希望这足以让我理解有关如何在 Shiny 网站上构建自定义输入/输出绑定(bind)的示例和解释:

http://shiny.rstudio.com/articles/building-inputs.html

但不幸的是,我没有,而且我似乎找不到任何使用最少工作代码的示例。 github 上的许多示例对我来说太复杂了,很可能是因为我对 javascript 的经验很少。以下是使用 javascript 自定义输入绑定(bind)的示例:

https://github.com/jcheng5/shiny-js-examples/tree/master/input

这是我尝试展开的输入和输出绑定(bind)的示例:

<script src="http://d3js.org/d3.v3.js"></script>
<script type="text/javascript">
(function(){
  // Probably not idiomatic javascript.

  this.countValue=0;

  // BEGIN: FUNCTION
  updateView = function(message) {

    var svg = d3.select(".d3io").select("svg")

    svg.append("text")
      .transition()
      .attr("x",message[0])
      .attr("y",message[1])
      .text(countValue)
      .each("end",function(){
        if(countValue<100) {
          countValue+=1;
          $(".d3io").trigger("change");
        }
      })
  }
  // END: FUNCTION

  //BEGIN: OUTPUT BINDING
  var d3OutputBinding = new Shiny.OutputBinding();
  $.extend(d3OutputBinding, {
    find: function(scope) {
      return $(scope).find(".d3io");
    },
    renderError: function(el,error) {
      console.log("Foe");
    },
    renderValue: function(el,data) {
      updateView(data);
      console.log("Friend");
    }
  });
  Shiny.outputBindings.register(d3OutputBinding);
  //END: OUTPUT BINDING

  //BEGIN: INPUT BINDING
  var d3InputBinding = new Shiny.InputBinding();
  $.extend(d3InputBinding, {
    find: function(scope) {
      return $(scope).find(".d3io");
    },
    getValue: function(el) {
      return countValue;
    },
    subscribe: function(el, callback) {
      $(el).on("change.d3InputBinding", function(e) {
        callback();
      });
    }
  });
  Shiny.inputBindings.register(d3InputBinding);
 //END: OUTPUT BINDING

})()
</script>

其中“d3io”是 ui 中的一个 div 元素,updateView() 是一个函数。这是用户界面:

#UI
library(shiny)

d3IO <- function(inputoutputID) {
  div(id=inputoutputID,class=inputoutputID,tag("svg","")) #; eerst zat ; erbij, maar werkt blijkbaar ook zonder
}

# Define UI for shiny d3 chatter application
shinyUI(pageWithSidebar(

  # Application title
  headerPanel("D3 Javascript chatter",
              "Demo of how to create D3 I/O and cumulative data transfer"),

  sidebarPanel(
    tags$p("This widget is a demonstration of how to wire shiny direct to javascript, without any input elements."),
    tags$p("Each time a transition ends, the client asks the server for another packet of information, and adds it
            to the existing set"),
    tags$p("I can't claim this is likely to be idiomatic javascript, because I'm a novice, but it allows d3 apps
            to do progressive rendering.  In real use, a more complex request/response protocol will probably be
            required.  -AlexBBrown")
  ),

  mainPanel(
    includeHTML("d3widget.js"),
    d3IO("d3io") #Creates div element that d3 selects
    )
))

这是服务器文件:

# SERVER
library(shiny)
# Define server logic required to respond to d3 requests
shinyServer(function(input, output) {

  # Generate a plot of the requested variable against mpg and only 
  # include outliers if requested
  output$d3io <- reactive(function() {
    if (is.null(input$d3io)) {
      0;
    } else {
      list(rnorm(1)*400+200,rnorm(1)*400+200);
    }
  })
})

具体问题:

1) server.r 似乎得到名为“d3io”(input$d3io) 的输入,因为这在 ui.r 中没有定义,我推断它一定来自 javascript 文件。它实际上指的是哪个元素?

2) 我无法理解自定义绑定(bind)部分:

var d3OutputBinding = new Shiny.OutputBinding();
  $.extend(d3OutputBinding, {
    find: function(scope) {
      return $(scope).find(".d3io");
    },
    renderError: function(el,error) {
      console.log("Foe");
    },
    renderValue: function(el,data) {
      updateView(data);
      console.log("Friend");
    }
  });
  Shiny.outputBindings.register(d3OutputBinding);

我的理解是:

创建一个新的 shiny outputbinding,首先找到类 .d3io(div 元素),如果错误则写入控制台“Foe”(这是特殊代码吗?),如果没有错误则使用函数 renderValue updateView 使用数据(Where它从哪里接收到这个值?)并写入控制台“Friend”。最后注册输出。

希望大家帮帮忙!我正在创建一个文档,其中包含有关“当您不知道任何 javascript 时学习如何将 javascript 实现为 shiny 的必要步骤”的步骤,我会喜欢的!:)

干杯, 长

最佳答案

嗨 Sweetbabyjesus(说起来很有趣)。你有两个问题:

1) The server.r seems to get input called "d3io" (input$d3io) since this is not defined in ui.r, I reasoned it must come from the javascript file. Which element does it actually refer to?

该短语 input$d3io 具有以下组件:

  • input 是传递给函数的参数 - 它是一个列表 存储应用程序中所有小部件的当前值。
  • $ 是成员选择器。
  • d3io 引用该id的div元素的内容 ('d3IO("d3io")') 在 UI 的主面板中。

2) I have trouble understanding the custom binding part:

var d3OutputBinding = new Shiny.OutputBinding();

没错,这将创建一个 Shiny.OutputBinding 实例并将其分配给变量 d3OutputBinding。

$.extend(d3OutputBinding, {
  find: function(scope) {
    return $(scope).find(".d3io");
  },
  renderError: function(el,error) {
    console.log("Foe");
  },
  renderValue: function(el,data) {
    updateView(data);
    console.log("Friend");
  }
});

此代码使用名为 findrenderErrorrenderValue 的三个函数扩展了 d3OutputBinding 的行为。 Shiny.OutputBinding 需要这三个函数。

find 是关键,因为它返回一个元素列表,这些元素应该通过它们的 el 参数传递给两个渲染函数。请注意,它返回的元素的 css 类是“d3io”——这与前面提到的 div 相同。

请注意,extend() 是 jQuery javascript 库的一个函数,在此上下文中的 $ 是 jQuery 对象的别名。

Shiny.outputBindings.register(d3OutputBinding);

让 Shiny 知道这个新配置的对象现在应该投入使用。

干杯,尼克

关于javascript - 将 javascript (d3.js) 绑定(bind)到 shiny,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26650561/

有关javascript - 将 javascript (d3.js) 绑定(bind)到 shiny的更多相关文章

  1. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  2. ruby-on-rails - 创建 ruby​​ 数据库时惰性符号绑定(bind)失败 - 2

    我正在尝试在Rails上安装ruby​​,到目前为止一切都已安装,但是当我尝试使用rakedb:create创建数据库时,我收到一个奇怪的错误:dyld:lazysymbolbindingfailed:Symbolnotfound:_mysql_get_client_infoReferencedfrom:/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundleExpectedin:flatnamespacedyld:Symbolnotfound:_mysql_get_client_infoReferencedf

  3. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  4. ruby-on-rails - Assets 管道损坏 : Not compiling on the fly css and js files - 2

    我开始了一个新的Rails3.2.5项目,Assets管道不再工作了。CSS和Javascript文件不再编译。这是尝试生成Assets时日志的输出:StartedGET"/assets/application.css?body=1"for127.0.0.1at2012-06-1623:59:11-0700Servedasset/application.css-200OK(0ms)[2012-06-1623:59:11]ERRORNoMethodError:undefinedmethod`each'fornil:NilClass/Users/greg/.rbenv/versions/1

  5. ruby-on-rails - Rails - 理解 application.js 和 application.css - 2

    rails新手。只是想了解\assests目录中的这两个文件。例如,application.js文件有如下行://=requirejquery//=requirejquery_ujs//=require_tree.我理解require_tree。只是将所有JS文件添加到当前目录中。根据上下文,我可以看出requirejquery添加了jQuery库。但是它从哪里得到这些jQuery库呢?我没有在我的Assets文件夹中看到任何jquery.js文件——或者直接在我的整个应用程序中没有看到任何jquery.js文件?同样,我正在按照一些说明安装TwitterBootstrap(http:

  6. ruby - ruby 中绑定(bind)对象的实际使用 - 2

    昨晚,我在思考我认为是高级ruby​​语言的功能,即Continuations(callcc)和Bindingobjects。我的意思是高级,因为我有静态类型的oo语言背景(C#、Java、C++),我最近才发现ruby​​,所以这些语言特性对我来说不是很熟悉。我想知道这些语言功能在现实世界中的用途是什么。根据我的经验,一切都可以用静态类型的oo语言来完成,但有时我不太同意。我想我在阅读SamRuby的那篇好文章时发现了Continuation的美妙之处/兴趣:http://www.intertwingly.net/blog/2005/04/13/Continuations-for-C

  7. ruby - 在 Mechanize 中使用 JavaScript 单击链接 - 2

    我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan

  8. node.js - 如何在 Travis CI 上的一个项目中运行 Node.js 和 Ruby 测试 - 2

    我有一个包含多个组件的存储库,其中大部分是用JavaScript(Node.js)编写的,一个是用Ruby(RubyonRails)编写的。我想要一个.travis.yml文件来触发一个运行每个组件的所有测试的构建。根据thisTravisCIGoogleGroupthread,目前还没有官方支持。我的目录结构是这样的:.├──构建服务器├──核心├──扩展├──网络应用├──流浪文件├──package.json├──.travis.yml└──生成文件我希望能够运行特定版本的Ruby(2.2.2)和Node.js(0.12.2)。我已经有了一个make目标,所以maketest在每

  9. javascript - jQuery 的 jquery-1.10.2.min.map 正在触发 404(未找到) - 2

    我看到有关未找到文件min.map的错误消息:GETjQuery'sjquery-1.10.2.min.mapistriggeringa404(NotFound)截图这是从哪里来的? 最佳答案 如果ChromeDevTools报告.map文件的404(可能是jquery-1.10.2.min.map、jquery.min.map或jquery-2.0.3.min.map,但任何事情都可能发生)首先要知道的是,这仅在使用DevTools时才会请求。您的用户不会遇到此404。现在您可以修复此问题或禁用sourcemap功能。修复:获取文

  10. ruby - svn ruby​​ 绑定(bind)是否作为 gem 提供? - 2

    我看到有几十个与svn相关的gem,但是我在其中任何一个上找到的少量文档表明它们是命令行包装器和杂项帮助程序。(svn命令、svn钩子(Hook)等)我在野外看到过执行以下操作的代码:require'svn/core'和SVN.Repos.add(...),但该模块的作者通过apt-get提取了他的svnruby​​工具。这对我来说不是一个选择,因为我正在开发一个windows/osx工具。Thispage列出了一些项目,但特别是,我需要一些可以访问svn+ssh存储库的东西,而且我没有时间花一半的时间来挖掘文档-十几个项目,试图引导每一个。我在寻找哪个gem?从那里开始,我很乐意挖掘

随机推荐