Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 Line Chart Filling at Arbitrary Line

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:

Line Chart

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.

like image 998
tshauck Avatar asked Feb 08 '13 03:02

tshauck


1 Answers

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

like image 160
Jonathan S. Avatar answered Oct 19 '22 03:10

Jonathan S.