d3.js:“无法读取未定义的属性‘权重’";手动定义力布局的节点和链接时 [英] d3.js: "Cannot read property 'weight' of undefined" when manually defining both nodes and links for force layout

查看:21
本文介绍了d3.js:“无法读取未定义的属性‘权重’";手动定义力布局的节点和链接时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试以这种方式同时设置节点和链接:

I tried setting both nodes and links at the same time this way:

var force = d3.layout.force()
    .size([w, h])
    .nodes(nodes)
    .links(connections)
    .start();

nodes = [{"name":"data_base_id", "kind":"subgenre"},...]
connections = [{"source":"name_of_node", "target":"name_of_other_node"},...]

我的数据可能没有连接,所以有必要定义节点,以便所有节点都得到渲染.定义类型非常容易.但我收到此错误;

I have data that may not have connections, so it is necessary to defined the nodes, so that all of the nodes get rendered. And defining the genres is pretty easy. but I get this error;

Cannot read property 'weight' of undefined

当我注释掉 .links(connections) 时,图形呈现(突出一堆散布在各处的点......)我如何让连接/链接与 d3 合作?

And when I comment out .links(connections) the graph renders (juts a bunch of dots scattered throughout...) How do I get the connections / links to cooperate with d3?

我正在阅读文档,显然源和目标必须是节点数组中节点的索引.无论如何要改变它吗?那么,我可以使用节点的名称而不是它在数组中的索引吗?

I was reading the docs, and apparently the source and target have to be INDEXES of the nodes in the nodes array. Is there anyway to change that? So, I can use the name of a node rather than the index it has in an array?

推荐答案

力导向布局使用边缘权重来计算布局.尝试为您的所有连接添加一个虚拟的 "weight":1.

The force-directed layout uses edge weights to calculate the layout. Try adding a dummy "weight":1 to all of your connections.

初始化链接的代码如下所示:

The code that initializes the links looks like this:

links.forEach(function(d) {
    if (typeof d.source == "number") { d.source = nodes[d.source]; }
    if (typeof d.target == "number") { d.target = nodes[d.target]; }
});

大概你可以调整它(在 d3 源代码中)以使用任何属性/类型.

Presumably you could tweak that (in the d3 source) to use any property/type.

这篇关于d3.js:“无法读取未定义的属性‘权重’";手动定义力布局的节点和链接时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆