I'm attempting to create a simple line chart with d3, however for some reason it's filling between the line and some midpoint. Here's the output:
My javascript is the following:
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);
Where visits is of the form:
visits = [{'datestamp': timestampA, 'visits': 1000},
{'datestamp': timestampB, 'visits': 1500}]
I'm pretty new at d3 so I'm sure it's something simple, but it's driving me crazy.
Thanks in advance.
The midpoint you're seeing is just the connection of the first and last point. This is because the path you've created has (by default) a black fill. Even though it's an open path (i.e., the first and last point are not actually connected), if filled, it will appear closed:
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.
Source: SVG specification via this SO answer
The solution here is to eliminate the fill and instead set a stroke. You can do this directly in JS with d3 or through CSS.
path.line
{
fill: none;
stroke: #000;
}
Demo showing both the CSS and JS method (commented out) on jsFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With