我正在尝试使用 d3 创建一个简单的折线图,但由于某种原因,它会在线和某个中点之间填充。这是输出:
我的 javascript 如下:
var width = 500,
height = 500,
padding = 10;
var extentVisits = d3.extent(visits, function(obj){
return obj['visits'];
});
var extentDates = d3.extent(visits, function(obj){
return obj['datestamp'];
});
var yScale = d3.scale.linear()
.domain(extentVisits)
.range([height - padding, padding]);
var xScale = d3.time.scale()
.domain(extentDates)
.range([0, width]);
var line = d3.svg.line()
.x(function(d) {
return xScale(d['datestamp']);
})
.y(function(d) {
return yScale(d['visits']);
})
d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append("g")
.attr("transform", "translate(5,5)")
.append('path')
.datum(visits)
.attr("class", "line")
.attr('d', line);
访问的形式是:
visits = [{'datestamp': timestampA, 'visits': 1000},
{'datestamp': timestampB, 'visits': 1500}]
我是 d3 的新手,所以我确信这很简单,但它让我抓狂。
提前致谢。
最佳答案
您看到的中点只是第一个点和最后一个点的连接点。这是因为您创建的路径(默认情况下)具有黑色填充。即使它是一条开放路径(即第一个点和最后一个点实际上并未连接),如果已填充,它将显示为闭合:
The fill operation fills open subpaths by performing the fill operation as if an additional "closepath" command were added to the path to connect the last point of the subpath with the first point of the subpath.
来源:SVG specification通过this SO answer
此处的解决方案是取消填充,而是设置描边。您可以直接在 JS 中使用 d3 或通过 CSS 执行此操作。
path.line
{
fill: none;
stroke: #000;
}
Demo showing both the CSS and JS method (commented out) on jsFiddle
关于javascript - d3 折线图任意线填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14765036/