[英]D3 Heatmap Syntax
So, my task is to help implement a few visuals in a web environment.所以,我的任务是帮助在 web 环境中实现一些视觉效果。 Specifically, I am trying to build a heat map from a simple dummy matrix representing a small dataset from a JSON file using d3 in JS.具体来说,我正在尝试从一个简单的虚拟矩阵构建一个热量 map,该虚拟矩阵表示来自 JSON 文件的小数据集,使用 JS 中的 d3。 The input data is this:输入数据是这样的:
{"data":[[8,2],[5,4],[9,6]]}
So, again, how would you visualize the above data in a heat map matrix using d3?那么,再次,您将如何使用 d3 在热 map 矩阵中可视化上述数据?
Sorry for the delay.抱歉耽搁了。
Hope below code helps..希望下面的代码有帮助..
<!DOCTYPE html>
<meta charset="utf-8">
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>
<script>
// set the dimensions and margins of the graph
var margin = {top: 30, right: 30, bottom: 30, left: 30},
width = 450 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
const data = {"data":[[8,2],[5,4],[9,6]]};
// 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 + ")");
// Labels of row and columns
var rows = [];
var cols = [];
var chartData = [];
data.data.forEach((item, i) => {
if( i === 0) {
item.forEach((itm , j) => {
cols.push("col" + j);
chartData.push({ row: "row" + i, col: "col" + j,value: itm});
});
} else {
item.forEach((itm , j) => {
chartData.push({ row: "row" + i, col: "col" + j, value: itm});
});
}
rows.unshift("row" + i);
})
// Build X scales and axis:
var x = d3.scaleBand()
.range([ 0, width ])
.domain(cols)
.padding(0.01);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
// Build X scales and axis:
var y = d3.scaleBand()
.range([ height, 0 ])
.domain(rows)
.padding(0.01);
svg.append("g")
.call(d3.axisLeft(y));
// Build color scale
var myColor = d3.scaleLinear()
.range(["white", "#69b3a2"])
.domain([1,100])
console.log(chartData);
//Read the data
svg.selectAll()
.data(chartData, function(d) {return d.row+':'+d.col;})
.enter()
.append("rect")
.attr("x", function(d) { return x(d.col) })
.attr("y", function(d) { return y(d.row) })
.attr("width", x.bandwidth() )
.attr("height", y.bandwidth() )
.style("fill", function(d) { return myColor(d.value)} )
</script>
Running example.. working example link运行示例..工作示例链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.