简体   繁体   English

使用D3的交互式条形图

[英]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). 我正在尝试在D3上绘制折线图,​​其中x变量是类似于2012-13的财政年度(而不是标准数据格式)。 As a result, I'm considering keeping the x values as strings. 结果,我正在考虑将x值保留为字符串。

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. 您没有显示的关键点是如何定义x缩放比例。 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. 比例尺确实NaN ,并且由于您获得的x值为NaN ,所以您的比例尺有些问题。

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. 如果您使用的是时间类型刻度( https://github.com/d3/d3-scale#scaleTime ),那么可以,它必须是有效的日期时间,即unix时间戳或日期对象。 You can use d3.timeParse ( https://github.com/d3/d3-time-format#timeParse ) to convert your string dates. 您可以使用d3.timeParse( https://github.com/d3/d3-time-format#timeParse )转换字符串日期。

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: 如果使用序数类型刻度,例如scalePoint( https://github.com/d3/d3-scale#scalePoint ),则可以使用字符串,但必须将所有日期字符串都传递给域:

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. 如果存在任何差距,这些差距也不会以序数类型的等级反映出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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