1
我需要創建一個覆蓋圖。我不明白如何實現覆蓋和應該是什麼樣的數據。也許熟悉d3.js並有技巧構建覆蓋圖的人可以解釋如何做到這一點。d3.js覆蓋圖
overlayGraph.js
var OverlayGraph = (function() {
return {
// Initializing the module
/*
dataFile - the path to the json file
selector - place of drawing chart
*/
init: function(dataFile, selector) {
d3.json(dataFile, data => {
this.drawOverlayGraph(data, selector);
});
},
// Draw out data
drawOverlayGraph: (data, selector) => {
// === BOILERPLATE ===
var margin = { top: 20, right: 100, bottom: 30, left: 100 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// === SVG Container ===
var svg = d3.select(selector)
.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 + ")");
// === SCALE ===
var xScale = d3.scale.linear()
.domain([0, d3.max(data, d => {
return +d.x;
})])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([0, d3.max(data, d => {
return +d.y;
})])
.range([height, 0]);
// === AXES ===
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.innerTickSize(-height)
.outerTickSize(0)
.tickPadding(10);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.innerTickSize(-width)
.outerTickSize(0)
.tickPadding(10);
// === Drawing axes ===
svg.append('g')
.attr('class', 'x axis')
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append('g')
.attr('class', 'y axis')
.call(yAxis);
// === VIZUALIZATION ===
var line = d3.svg.line()
.interpolate('basis')
.x(d => {
return xScale(d.x);
})
.y(d => {
return yScale(d.y);
});
svg.append('path')
.attr('d', line(data))
.attr('class', 'line');
}
}
})();
OverlayGraph.init('data.json', 'body');
我的數據是這樣的:
[
{
"x": "0",
"y": "5"
},
...
]
問候
感謝您的諮詢。我在我的json文件中添加了一些字段並使用了您的解決方案。結果證明這是必要的。再次感謝。 – Alexander