我需要创建一个叠加图。我不明白如何实现叠加层以及应该是什么类型的数据。也许谁熟悉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"
},
...
]
此致
答案 0 :(得分:0)
你想要的是一个区域https://github.com/d3/d3-shape/blob/master/README.md#areas 你必须找到一种方法来定义你的每一个点的区域的底部值和顶部值,然后做一个
var area = d3.area()
.x(function(d, i) { return x(d.data.date); })
.y0(function(d) { return y(d.bottomValue); })
.y1(function(d) { return y(d.topValue); });
g.append("path")
.datum(data)
.attr("fill", "steelblue")
.attr("d", area);