2017-02-14 7 views
2

Я хотел бы первым, чтобы решить мои намеренияD3.js Tree проход node.name по щелчку на R Shiny

1) Создать предопределенный D3.js складного дерева в Shiny

2) На щелчку node имя этого конкретного узла передается из D3.js в R для дальнейших операций.

Ну, на данный момент у меня есть предопределенное дерево разворачивающегося D3.js в Shiny. Я предоставляю код для js, server.R и ui.R ниже. Теперь на данный момент у меня есть интерактивная графика, но я хотел бы сделать еще один шаг вперед.

Как только я нажимаю на узел, я хотел бы получить имя узла как переменную.

Я сделал свое исследование (в основном здесь: https://github.com/metrumresearchgroup/SearchTree), поэтому я знаю, что мне нужно использовать d3OutputBinding для создания новой переменной. Далее я узнал, что

.on('click', function(node) { 
      alert(node.name); 

, по крайней мере, вывести сообщение с именем узлов. Поэтому я полагаю, я должен использовать что-то вроде

var d3OutputBinding = new Shiny.OutputBinding(); 
$.extend(d3OutputBinding, { 
    find: function(scope) { 
     return $(scope).find('.div_tree2'); 
    }, 
    renderValue: function(el) { 
     var svg = d3.select(el).select("svg"); 
... 
function update(source) { 
... 
nodeEnter = node.enter().append("g") 
.on('click', function(node) {var nodes1 = node.name; }); 
... 
Shiny.onInputChange(".nodesData", JSON.decycle(nodes1)); 
... 
} // end of renderValue 
}); // end of .extend 

и подключить его к server.R с помощью реактивной функции (вход $ .nodesData).

К сожалению, я слишком глуп, чтобы этого достичь. Поэтому я прошу вас проконсультировать вас.

Как уже говорилось, я бы предоставил свои коды. Здесь идет мой d3script_tree.js

Shiny.addCustomMessageHandler("jsondata_tree", 
    function(message){ 
var treeData = [ 
    { 
    "name": "Parent", 
    "parent": "null", 
    "children": [ 
     { 
     "name": "A", 
     "parent": "Parent" 
     }, 
     { 
     "name": "B", 
     "parent": "Parent" 
     } 
    ] 
    } 
]; 


// ************** Generate the tree diagram ***************** 
var margin = {top: 20, right: 120, bottom: 20, left: 120}, 
    width = 960 - margin.right - margin.left, 
    height = 250 - margin.top - margin.bottom; 

var i = 0, 
    duration = 750, 
    root; 

var tree = d3.layout.tree() 
    .size([height, width]); 

var diagonal = d3.svg.diagonal() 
    .projection(function(d) { return [d.y, d.x]; }); 

var svg = d3.select("#div_tree2").append("svg") 
    .attr("width", width + margin.right + margin.left) 
    .attr("height", height + margin.top + margin.bottom) 
    .append("g") 
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

root = treeData[0]; 
root.x0 = height/2; 
root.y0 = 0; 

update(root); 

d3.select(self.frameElement).style("height", "500px"); 


function update(source) { 

    // Compute the new tree layout. 
    var nodes = tree.nodes(root).reverse(), 
     links = tree.links(nodes); 

    // Normalize for fixed-depth. 
    nodes.forEach(function(d) { d.y = d.depth * 180; }); 

    // Update the nodes… 
/* var node = svg.selectAll("g.node") 
    .data(nodes, function(d) { return d.id || (d.id = ++i); }) 
*/ 
    var node = svg.selectAll("g.node") 
     .data(nodes, function(d) { return d.id || (d.id = ++i); }) 

    // Enter any new nodes at the parent's previous position. 
    var nodeEnter = node.enter().append("g") 
     .attr("class", "node") 
     .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }) 
     //.on("click", click); 
     .on('click', function(node) { 
     alert(node.name); 
    }); 

    nodeEnter.append("circle") 
     .attr("r", 1e-6) 
     .style("fill", function (d) { return '#05415A'; }) 
     //.style("fill", function(d) { return d._children ? "#C00000" : "#fff"; }); 

    nodeEnter.append("link") 
    .style("stroke-width", "3px");  

    nodeEnter.append("text") 
     .attr("x", function(d) { return d.children || d._children ? -13 : 13; }) 
     .attr("dy", ".35em") 
     .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) 
     .text(function(d) { return d.name; }) 
     .style("fill-opacity", 1e-6); 

    // Transition nodes to their new position. 
    var nodeUpdate = node.transition() 
     .duration(duration) 
     .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }); 

    nodeUpdate.select("circle") 
     .attr("r", 10) 
     .style("fill", function (d) { return '#05415A'; }) 
    // .style("fill", function(d) { return d._children ? "#C00000" : "#fff"; }); 

    nodeUpdate.select("text") 
     .style("fill-opacity", 1); 

    nodeUpdate.select("link") 
    .style("stroke-width", "3px"); 

    // Transition exiting nodes to the parent's new position. 
    var nodeExit = node.exit().transition() 
     .duration(duration) 
     .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; }) 
     .remove(); 

    nodeExit.select("circle") 
     .attr("r", 1e-6); 


    nodeExit.select("text") 
     .style("fill-opacity", 1e-6); 

    // Update the links… 
    var link = svg.selectAll("path.link") 
     .data(links, function(d) { return d.target.id; }); 

    // Enter any new links at the parent's previous position. 
    link.enter().insert("path", "g") 
     .attr("class", "link") 
     .attr("d", function(d) { 
     var o = {x: source.x0, y: source.y0}; 
     return diagonal({source: o, target: o}); 
     }); 

    // Transition links to their new position. 
    link.transition() 
     .duration(duration) 
     .attr("d", diagonal); 

    // Transition exiting nodes to the parent's new position. 
    link.exit().transition() 
     .duration(duration) 
     .attr("d", function(d) { 
     var o = {x: source.x, y: source.y}; 
     return diagonal({source: o, target: o}); 
     }) 
     .remove(); 

    // Stash the old positions for transition. 
    nodes.forEach(function(d) { 
    d.x0 = d.x; 
    d.y0 = d.y; 
    }); 
} 

// Toggle children on click. 
function click(d) { 
    if (d.children) { 
    d._children = d.children; 
    d.children = null; 
    } else { 
    d.children = d._children; 
    d._children = null; 
    } 
    update(d); 
} 
    }); 

Следующий У меня есть ui.R, ссылающийся на него. Стили CSS не имеют никакого значения, поэтому его можно игнорировать.

library(shinydashboard) 
library(shinyjs) 


sidebar <- dashboardSidebar(
    sidebarMenu(
    menuItem("Toy example", tabName = "toy", icon = icon("cog")) 
) 
) 

body <- dashboardBody(
    tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "custom.css") 
), 
    tabItems(
    tabItem(tabName = "toy", 
      tags$div(class="d3-div", 
        #to style to d3 output pull in css 
        tags$head(tags$link(rel = "stylesheet", type = "text/css", href = "style.css")), 
        #load D3JS library 
        tags$script(src="d3.min.js"), 
        #tags$script(src="https://d3js.org/d3.v3.min.js"), 
        #load javascript 
        tags$script(src="d3script_tree.js"), 
        #create div referring to div in the d3script 
        tags$div(id="div_tree2")) 
      ) 
) 
) 

# Put them together into a dashboardPage 
dashboardPage(
    dashboardHeader(title = "Toy Example"), 
    sidebar, 
    body 
) 

И, наконец, сервер.R запускает этот Java-скрипт.

library(shiny) 
library(shinyjs) 

shinyServer(function(input, output, session) { 
    options(shiny.maxRequestSize=30*1024^2, shiny.usecairo=T) 

    var_json_tree <- toJSON(1, pretty = T) 
    #push data into d3script 
    session$sendCustomMessage(type="jsondata_tree",var_json_tree) 
}) 
+0

При попытке воспроизвести: Когда я Ĉ & р ваш JS код, который я получаю сообщение об ошибке на строки 72, 152 и 162. Собираетесь ли вы закрыть обработчик сообщения в строке 72? – BigDataScientist

ответ

1

Я не думаю, что вам нужно Shiny.OutputBinding(); часть для этого, вы можете просто использовать Shiny.onInputChange передать имя узла обратно в server.R.

я не бегал весь свой код, но вы можете попробовать:

.on('click', function(node) { 
      Shiny.onInputChange("node_name", node.name); 
} 

И в server.R, input$node_name будет содержать имя узла.

EDIT

Чтобы падающее дерево, вы можете просто изменить функцию click в конце вашего JavaScript:

function click(d) { 
    Shiny.onInputChange("node_name", d.name); 
    if (d.children) { 
    d._children = d.children; 
    d.children = null; 
    } else { 
    d.children = d._children; 
    d._children = null; 
    } 
    update(d); 
} 
    }); 
+0

Отлично! Также можно создать несколько переменных, например parent.name, и передать их. – Alex

+0

Извините, но теперь у меня есть еще одна проблема: поскольку я удалил '.on ('click', click)' мое дерево больше не сбрасывается :(Просто добавив его в 'function (node)' не помогает. ve попытался добавить еще один.on ('click', click) ', но это не сделало трюк – Alex

+1

Добавьте конец вашего javascript, есть функция' function click (d) '. Вставьте код из этой функции в новую. Убедитесь, что вы также заменили 'd' на' node'. или добавьте Shiny.onInputChange прямо к нему – NicE