简体   繁体   中英

Interactive bar chart using D3

I'm trying to plot a line chart on D3, where the x-variable is a financial year like 2012-13 (instead of a standard data format). As a result, I'm considering keeping the x values as strings.

I have the following code for defining the line

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

Then, I read the data, and add the line to the chart:

d3.csv("data.csv", function(error, data) {
    data.forEach(function(d) {
        d.date = d.date);
        d.close = +d.close;
    });

    ...

    // Add the valueline path.
    svg.append("path")
        .attr("class", "line")
            .attr("d", valueline(data));

        ...

        // add axes etc

});

This isn't working and I'm getting the following error:

Error: <path> attribute d: Expected number, "MNaN,190.81307074…".

Does that mean a line chart necessarily expects a date or a number?

The data is as follows:

date,close
2012-13,58.13
2013-14,53.98
2014-15,67.00
2015-16,89.70
2016-17,99.00

The crucial bit you're not showing is how you are defining your x-scale. The line doesn't care what your data is; the scale does and since you are getting NaN for your x value, something is with your scale is wrong.

If you are using a time type scale ( https://github.com/d3/d3-scale#scaleTime ), then yes, it has to be a valid datetime, IE a unix timestamp or date object. You can use d3.timeParse ( https://github.com/d3/d3-time-format#timeParse ) to convert your string dates.

If you are using an ordinal type scale, such as scalePoint ( https://github.com/d3/d3-scale#scalePoint ), then you can use strings, but would have to pass all your date strings in for the domain:

x.domain(data.map(function(d) { return d.date; }));

If there are any gaps, those would also not be reflected with an ordinal type scale.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM