对于每个节点,我都有一个圆圈,可以借助一个函数对其进行着色ColorType(d)
:
node.append("circle")
.attr("r", 20)
.attr("y", -25)
.style("fill", function(d) { return ColorType(d); })
.style("stroke-width",0.5)
.style("stroke",'black')
.attr("opacity", "1");
我的ColorType
功能是
function ColorType(d){
for (var i = 0; i < TypesTab.length; i++) {
if (d.type == TypesTab[i].type) { return ColorAction;}
}
}
在上面的函数中,d.type
是我的节点的类型(请参阅下面的json文件strucutre)。并且TypesTab[i].type
将我的每个类型分别存储在类型中,检查节点类型是否与类型中类型的值之一相同,如果是,则应用ColorAction
为节点圆圈上色的类型。
这是ColorAction
代码,它嵌入在每个颜色选择器容器中,该容器在类型中附加到每种类型,该列表插入到#filterColor
html dom中。因此,每种类型都有一个颜色选择器容器,该容器只能为自己的类型着色。
$(document).ready(function () {
$.getJSON("databeta.json", function (obj) {
$('#filterColor').data('types', obj.types.map(function (o) {
// console.log(o.type);
return o.type;
})).append(obj.types.map(function (o) {
return '<li>' + o.type + '<input class="color-picker" type="text"/></li>';
}).join(''));
var data = $('#filterColor').data('types'); //stores all types
mynodes = obj.nodes;
console.log("mynodes : ", mynodes); //array of all my nodes
console.log("mynodes : ", mynodes[3].type); //reading the type of the fourth object in the nodes array
$("#filterColor .color-picker").each(function(){
$(this).spectrum({
color: (function (m, s, c) {
return (c ? arguments.callee(m, s, c - 1) : '#') +
s[m.floor(m.random() * s.length)]
})(Math, '0123456789ABCDEF', 5), //generate random initial color for each container
preferredFormat: "rgb",
showInput: true,
showPalette: true,
showAlpha: true,
palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]],
change: function(color) {
MyNode = d3.select("#node").selectAll(".entreprise").select("circle");
MyNode.style("fill", function(d) {
return d3.rgb(color.toHexString())
});
Coloration = d3.rgb(color.toHexString());
}
});
});
});
});
问题是,当我在ColorType(d)
函数中对类型进行硬编码时,
if (d.type == "school") { return ColorAction;}
它仅成功为学校键入的节点上色。但是,如果我想使其动态化,以便它使用颜色选择器所分配的类型为节点着色,则它会失败,因为我无法使用each
of进行连接o.type
。所以,问题是要通过each
的o.type
进入ColorAction
和/或ColorType(d)
使得每个容器的颜色仅其自己的类型的节点。
这里是一个unsuccessfull尝试,因为它没有考虑到o.type
并读取type
的类型从一个全局变量(TypesTab
)持有的所有type
S IN类型:
function ColorType(d){
for (var i = 0; i < TypesTab.length; i++) {
if (d.type == TypesTab[i].type) { return ColorAction;}
}
}
下面是json结构:
{
"nodes": [
{
"type": "school",
"country": "US",
"name": "saint peter's",
"id": 1006
},
{
"type": "univeristy",
"country": "Brazil",
"name": "saint joseph's",
"id": 1007
}
...
],
"links": [
{
"source": 1006,
"target": 1007,
"value": 20
},
...
],
"types": [
{
"type": "school",
"image": "image01"
},
{
"type": "univeristy",
"image": "image02"
},
{
"type": "company",
"image": "image03"
},
...
]
}
这就是我读取/导入JSON的方式。for中的内容是基本的,因此您需要更改该部分以适合您的需求。
d3.json("data.json", function (error, data) { console.log(d3.values(data)); // do this as a check for (var d in data) { d.nodes = +d.nodes; d.links = +d.links; d.types = +d.types; } // svg can go here })
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句