Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build D3js Area Chart with negative values

Tags:

d3.js

We have an example for bar chart with negative values...Bar Chart with negative values

Is there any similar example for area chart?

like image 280
Santosh Avatar asked Dec 15 '22 16:12

Santosh


2 Answers

This is an old question but I thought I may be able to shed some light for anyone else that lands here. When setting up your svg area simply set y0 to your charts 0 line position. For example:

d3.svg.area()
  .x(function(d) {
    return x(d.x);
  })
 .y0(function() {
   return y(0);
 })
 .y1(function(d) {
   return y(d.y);
 });

Hope this helps!

like image 63
Geoff Woodburn Avatar answered Dec 18 '22 05:12

Geoff Woodburn


Sure, I've created a fiddle based off Mike Bostock's post on reusable charts: http://jsfiddle.net/C5gYv/

Essentially what I do is check if the data is positive or negative and then set y0 and y1 respectively:

    area = d3.svg.area()
        .x(X)

    ...

        g.select(".area").attr("d",
            area.y1(function (d) {
                // the highest point
                if (d[1] <= 0) {
                    return yScale(0);
                } else {
                    return Y(d);
                }
            })
                .y0(function (d) {
                // the lowest point
                if (d[1] <= 0) {
                    return Y(d);
                } else {
                    return yScale(0);
                }
            }));

Hope that helps!

like image 36
Hardbyte Avatar answered Dec 18 '22 05:12

Hardbyte