【发布时间】:2014-10-11 14:12:36
【问题描述】:
我正在尝试将 R 中呈现的热图和树状图连接到 InCHlib JavaScript 库,具体取决于用户通过 Shiny 的输入。为了在输入更改时更新热图,我需要编写自定义输出绑定。我研究了教程和我在网上找到的一堆示例,但不知何故我没有得到任何输出。
ui.R
library(shiny)
soucre("HeatMapBinding.R")
shinyUI(
fluidPage(
...
mainPanel(
heatMapOutput("heatmap")
)
)
)
服务器.R
source("InCHlibUtils.R")
shinyServer(function(input, output, session) {
output$heatmap <- reactive({
if(input$get == 0)
return()
isolate({
data <- retrieveData()
hc.row <- hclust(dist(data), input$cluster.method)
hc.col <- hclust(dist(t(data)), input$cluster.method)
map <- InCHlib(hc.row, hc.col, data)}) # Nested List, JSON ready
# How I previously wrote the data to a file in the correct JSON format
# for the javascript library to pick up later. This was of course not dynamic
# writeLines(toJSON(map), "heatmap.json")
})
})
HeatMapBinding.R
library(shiny)
heatMapOutput <- function(inputId, width="1000px", height="1200px") {
style <- sprintf("width: %s; height: %s;", validateCssUnit(width), validateCssUnit(height))
tagList(
singleton(tags$head(
tags$script(src="scripts/jquery-2.0.3.min.js"),
tags$script(src="scripts/kinetic-v5.0.0.min.js"),
tags$script(src="scripts/inchlib-1.0.0.js"),
tags$script(src="scripts/heatmap.js")
)),
div(id=inputId, class="InCHlib-heatmap", style=style,
tag("div", list())
)
)
}
heatmap.js
(function() {
var binding = new Shiny.OutputBinding();
binding.find = function(scope) {
return $(scope).find(".InCHlib-heatmap");
};
binding.renderValue = function(el, data) {
var $el = $(el);
// Original javascript that worked stand alone
$(document).ready(function() { //run when the whole page is loaded
window.inchlib = new InCHlib({ //instantiate InCHlib
target: "inchlib", //ID of a target HTML element
metadata: false, //turn off the metadata
max_height: 1200, //set maximum height of visualization in pixels
width: 1000, //set width of visualization in pixels
heatmap_colors: "Greens", //set color scale for clustered data
metadata_colors: "Reds", //set color scale for metadata
});
// originaly a file was loaded, now i want to load the data(frame)
// inchlib.read_data_from_file(heatmap.json) //read input json file
if(data != null){
inchlib.read_data(data); //read input json data?
inchlib.draw(); //draw cluster heatmap
}
};
};
//Tell Shiny about our new output binding
Shiny.outputBindings.register(binding, "shinyjsexamples.InCHlib-heatmap");
})();
如果我没记错的话,我不需要在 server.R 中定义 renderHeatMap 函数,因为我的数据已经准备好 JSON 了吗?
当我调试我的 JavaScript heatmap.js 时,renderValue 函数会在页面加载后立即调用,此时没有可用数据。这是唯一一次调用该函数。我知道事情的 R 方面一直工作到 output$heatmap (如果我确实写了那个 json 文件,那个文件看起来很好)。如果我调试我的 JavaScript,我会看到加载了正确的数据。
我觉得我没有完全理解自定义输出绑定机制。因此,如果有人能指出我正确的方向,那将是一个很大的帮助。
提前致谢
【问题讨论】:
标签: javascript r shiny