javascript - 如何使用 d3 将 json 渲染为网络图
问题描述
这就是我的数据的样子
"nodes": [
{
"name": "sender"
},
{
"name": "0"
},
{
"name": "1"
},
{
"name": "2"
},
{
"name": "3"
},
{
"name": "4"
},
{
"name": "5"
},
{
"name": "6"
},
{
"name": "7"
},
{
"name": "8"
},
{
"name": "9"
},
{
"name": "10"
},
{
"name": "11"
},
{
"name": "12"
},
{
"name": "13"
},
{
"name": "14"
},
{
"name": "15"
},
{
"name": "16"
},
{
"name": "17"
},
{
"name": "18"
},
{
"name": "19"
},
{
"name": "20"
},
{
"name": "21"
},
{
"name": "22"
},
{
"name": "23"
},
{
"name": "24"
},
{
"name": "25"
},
{
"name": "26"
},
{
"name": "27"
},
{
"name": "28"
},
{
"name": "29"
},
{
"name": "[16]"
}
],
"links": [
{
"source": "sender",
"target": "[16]"
}
]
}
我需要使用 d3 在屏幕上渲染这些。这就是我的代码的样子:
function drawChart(data) {
// set the dimensions and margins of the graph
// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 40},
width = 400 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Initialize the links
var link = svg
.selectAll("line")
.data(data.links)
.enter()
.append("line")
.style("stroke", "#aaa")
// Initialize the nodes
var node = svg
.selectAll("circle")
.data(data.nodes)
.enter()
.append("circle")
.attr("r", 20)
.style("fill", "#69b3a2")
// Let's list the force we wanna apply on the network
var simulation = d3.forceSimulation(data.nodes) // Force algorithm is applied to data.nodes
.force("link", d3.forceLink() // This force provides links between nodes
.id(function(d) { return d.id; }) // This provide the id of a node
.links(data.links) // and this the list of links
)
.force("charge", d3.forceManyBody().strength(-400)) // This adds repulsion between nodes. Play with the -400 for the repulsion strength
.force("center", d3.forceCenter(width / 2, height / 2)) // This force attracts nodes to the center of the svg area
.on("end", ticked);
}
根据其中一个答案,我们需要创建一个层次结构,以便 d3 将其呈现为图形,但我不知道如何合并它。这是我第一次与 D3 合作,因此任何潜在客户都会有所帮助
解决方案
推荐阅读
- caching - MAMP - 本地主机上的页面不刷新 (PHP 7.3.8)
- java - 使用 Spring Boot 从 Kafka 消费时启动 gradle 项目时出错:“java.lang.IllegalStateException: Error processing condition on ...”
- php - VAR_DUMP 显示结果时未生成 JSON
- c# - 与工厂方法的定义混淆
- c++ - 前向声明函数和 SFINAE
- algorithm - 这个函数的空间和时间复杂度是多少,它根据从尾部的位置获取链表中的节点?
- c# - 直接从 AWS S3 存储桶读取对象并使用 SpreadsheetGear 返回工作簿
- ios - 快速导航控制器在尝试导航到另一个视图控制器时返回 nil
- javascript - react-redux 中 action-reducer 链如何工作
- token - SagePay 令牌问题