Santosh
Santosh

Reputation: 885

Build D3js Area Chart with negative values

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

Is there any similar example for area chart?

Upvotes: 4

Views: 3104

Answers (3)

Sachin
Sachin

Reputation: 2148

I have updated the JSFiddle of @Hardbyte because I think it was not proper.

Here is the updated fiddle new fiddle.

What I have changed is -

// Update the area path.
        if (showArea) {
            g.select(".area").attr("d",
            area.y1(function (d) {
                // the highest point
                return Y(d);
            })
            .y0(function (d) {
                // the lowest point
                return yScale(0);
            }));
        }

Upvotes: 0

Geoff Woodburn
Geoff Woodburn

Reputation: 126

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!

Upvotes: 10

Hardbyte
Hardbyte

Reputation: 1639

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!

Upvotes: 2

Related Questions