d3.js - d3.js,我想知道如何根据网络图的节点将此代码颜色
问题描述
从 .json 文件中,我想绘制网络图。
特别是,我想为特定节点赋予不同的颜色,例如 .json 文件中的红色、蓝色。
.json 文件格式
{
"nodes": [
{"id": "Myriel", "group": 1},
{"id": "Napoleon", "group": 1}
],
"links" : [
{"source": "Napoleon", "target": "Myriel", "value": 1}
]
}
我试图为选定的节点着色。所以,我添加了这样的代码:
.style("fill", function(d){
d.color = color(d.name('Myriel'));
return d.color;})
如果不添加此代码,它可以工作。
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.links line {
stroke: #aaa;
}
.nodes circle {
pointer-events: all;
stroke: none;
stroke-width: 40px;
}
</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
d3.json("miserables.json", function(error, graph) {
if (error) throw error;
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line");
myCategory3("Myriel");
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.style("fill", function(d){
d.color = color(d.name('Myriel'));
return d.color;})
.attr("r", 2.5)
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
node.append("title")
.text(function(d) { return d.id; });
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked() {
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; });
}
});
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
</script>
任何知道如何添加颜色选择节点的人,请帮助我,谢谢。
解决方案
推荐阅读
- prometheus - 是否可以使用 Grafana 触发 Ansible Tower 剧本?
- jira - 自昨天以来查找 Jira 状态更改的问题
- deployment - Github Actions : 在自托管上结帐最后一个版本
- angularjs - 计算两个日期之间的剩余天数,不包括周末和公共假期
- pip - 无法在 MacBook Air M1 中运行 PIP3
- python - 在 Python 中重命名文件时出现 FileNotFoundError,但文件确实被重命名了
- c - 如果搜索值不存在,需要知道程序是否导致缓冲区越界或无限长搜索
- javascript - selectize.js 选择下拉显示默认打开
- python - 在python中为函数参数设置特定的值范围
- r - 格式化数据表以进行正态性分析和绘图