效果截图
index.html文件内容
// 基础参数
const matrixWidth = 650;
const matrixHeight = 650;
var margin = {
top: 70,
left: 70,
right: 40,
bottom: 40
};
var textFontSize = 10;
var linkObj = {}, nodeObj = {};
const matrixSvg = d3.select("#matrix-chart")
.append("svg")
.attr("viewBox", [0, 0, matrixWidth, matrixHeight]);
var matrixColor = d3.scaleOrdinal(d3.schemeCategory10);
index.js文件内容
辅助函数
/*
* 矩阵方块
* */
function Cube(obj) {
matrixSvg.append("rect")
.attr("class", "cube")
.attr("id", `cube-` + obj.id)
.attr("width", obj.w)
.attr("height", obj.h)
.attr("x", obj.x)
.attr("y", obj.y)
.style("fill", obj.color)
.style("stroke", "#fff")
.style("stroke-width", 1)
;
}
/*
* 水平文本标签
* */
function HText(obj) {
matrixSvg.append("text")
.attr("id", `text-${obj.id}-1`)
.attr("class", `text`)
.attr("dx", obj.x)
.attr("dy", obj.y)
.style("font-size", textFontSize)
.style("text-anchor", "end")
.text(obj.text);
}
/*
* 垂直文本标签
* */
function VText(obj) {
matrixSvg.append("g")
.attr("id", `box-${obj.id}-2`)
.attr("transform", `translate(${obj.x},${obj.y})`)
.append("text")
.attr("class", `text`)
.attr("id", `text-${obj.id}-2`)
.style("font-size", textFontSize)
.style("text-anchor", "start")
.text(obj.text)
.attr("transform", d => `rotate(${-90}) `)
;
}
图形函数
/*
* 绘制矩阵图形
* */
function MatrixChart(data) {
var length = data.nodes.length;
var CubeW = (matrixWidth - margin.left - margin.right) / length;
var CubeH = (matrixHeight - margin.top - margin.bottom) / length;
var cubeId = "";
for (var i = 0; i < length; i++) {
cubeId = `${data.nodes[i].id}-${data.nodes[0].id}`;
Cube({
id: cubeId,
x: margin.left,
y: i * CubeH + margin.top,
w: CubeW,
h: CubeH,
color: CubeColor(cubeId)
});
var text = `${data.nodes[i].itsc}`;
HText({
id: data.nodes[i].id,
x: margin.left - 10,
y: i * CubeH + margin.top + CubeH - 2,
text: text
});
VText({
id: data.nodes[i].id,
x: i * CubeW + margin.left + CubeW - 2,
y: margin.top - 10,
text: text
});
for (var j = 1; j < length; j++) {
cubeId = `${data.nodes[i].id}-${data.nodes[j].id}`;
Cube({
id: cubeId,
x: j * CubeW + margin.left,
y: i * CubeH + margin.top,
w: CubeW,
h: CubeH,
color: CubeColor(cubeId)
});
}
}
}
加载数据
/*
* 加载数据
* */
d3.json("data.json").then(function (res) {
var data = {
edges: [],
nodes: []
}
res.nodes.forEach(function (item) {
if (nodeObj[item.id] === undefined) {
nodeObj[item.id] = item;
}
data.nodes.push(item);
});
res.edges.forEach(function (item) {
data.edges.push(item);
linkObj[`${item.source}-${item.target}`] = item;
});
MatrixChart(data);
});
QQ:782975769