Ale*_*xey 24 javascript charts
我需要能够在JavaScript中绘制如下图形:

我知道拉斐尔图书馆,但它只是绘制任意形状.
我有一些预定义的节点类型(图像上的彩色节点)和每个节点附近/内部的文本.这个库似乎没有处理这种情况.我如何在JavaScript中执行此操作?如果这已由另一个库完成,我该如何使用该库来解决此问题?
Ian*_*Ian 41
网络是一个快速发展的世界,所以这个答案有点过时了.考虑到这一点,我已经刷新了这个答案,使其适用于2016年.
我想补充一点,我只是D3.js在这个新列表中使用过,它的功能和灵活性使得我从未需要找到替代方案.以下是力导向的示例实现.
var width = 960,
    height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);
d3.json("https://gist.githubusercontent.com/mbostock/4062045/raw/4176c7d0c0c5ce15630d16072da0af67bb50eb6a/miserables.json", function(error, graph) {
  if (error) throw error;
  force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();
  var link = svg.selectAll(".link")
      .data(graph.links)
    .enter().append("line")
      .attr("class", "link")
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });
  var node = svg.selectAll(".node")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d) { return color(d.group); })
      .call(force.drag);
  node.append("title")
      .text(function(d) { return d.name; });
  force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });
    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  });
});Run Code Online (Sandbox Code Playgroud)
.node {
  stroke: #fff;
  stroke-width: 1.5px;
}
.link {
  stroke: #999;
  stroke-opacity: .6;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>Run Code Online (Sandbox Code Playgroud)
有许多库用于在浏览器中绘制这种输出,你已经提到了Raphael,其他包括:
我个人会推荐后者,D3取决于您希望显示的项目数量以及您需要的浏览器支持,因为它有详细记录,功能强大且易于使用.查看这个Github项目,获取一个强制定向库的示例.
为完成您设定的任务,您需要进行的更改是:
1)通过修改以下功能来更改数据的来源:
d3.json("flare.json", function(json) {
   root = json;
   root.fixed = true;
   root.x = w / 2;
   root.y = h / 2 - 80;
   update();
 });
Run Code Online (Sandbox Code Playgroud)
将更改d3.json("flare.json")指向服务器上的其他文件/ URL.如果你希望并使用类似的回调方法,可以用jQuery做同样的事情.
2)要根据不同的类别为节点着色,您需要更改以下部分:
// Update the nodes…
  node = vis.selectAll("circle.node")
      .data(nodes, function(d) { return d.id; })
      .style("fill", color);
Run Code Online (Sandbox Code Playgroud)
更改.style("fill", color);为以下内容:
.style("fill", function(d) { 
    switch(d.category) {
       case A: return "#FF0000";
       case B: return "#00FF00";
       default: return "#0000FF";
    }
});
Run Code Online (Sandbox Code Playgroud)
其中category是JSON数据对象上要更改的属性.