Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two lined D3.js line chart, with one line starting at different position

I am creating a Line Chart in D3.js with two lines. The second line needs to start (and be rendered) and at a later date than the first. The data I am using for the graph looks like this:

var data = [{
    date: "1-May-12",
    close: "58.13",
    open: "58.13"
}, {
    date: "30-Apr-12",
    close: "53.98",
    open: "53.98"
}, {
    date: "27-Apr-12",
    close: "67.00",
    open: "67.00"
}, {
    date: "26-Apr-12",
    close: 0,
    open: "89.70"
}, {
    date: "25-Apr-12",
    close: 0,
    open: "99.00"
}];

In my current example, both lines are plotted but the second line (close) is plotted at the bottom of the graph and then jumps to the third value. I need the line to start when there is data. I have tried changing the value from 0 to null without any success. How do I change the graph so the second line only starts when there is actual data?

See this JSFiddle for the example: https://jsfiddle.net/londonfed/hprd452q/4/

Thanks in advance.

like image 997
londonfed Avatar asked Oct 22 '25 04:10

londonfed


1 Answers

You can define where the line is and isn't defined using defined(). For example to set the line as undefined when it is 0 (or less) you can use:

var valueline = d3.svg.line()
   .defined(function(d) {return d.close > 0})
   .x(function(d) { return x(d.date); })
   .y(function(d) { return y(d.close); });

This will cause the line not to draw anywhere d.close is <= 0.

Dos for defined() here: https://github.com/d3/d3-shape/blob/master/README.md#line_defined

Here's an updated Fiddle: https://jsfiddle.net/4hkLqn84/

like image 55
Mark Avatar answered Oct 23 '25 18:10

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!