javascript - 如何将 JSON 数据添加到 nvd3 图表

标签 javascript html json d3.js nvd3.js

我是 Javascript 新手,在我的代码中找不到错误。 我在这里使用 NVD3 图表。它是一个基于时间序列的图表,包含特定股票的日期和收盘价。数据范围从2005年至今。

这是代码

var data= JSON.parse("Data.JSON")

nv.addGraph(function() {
 var chart = nv.models.lineChart()
              .margin({top: 70, right: 70, bottom: 70, left: 70})  
              .useInteractiveGuideline(true)  
              .transitionDuration(100)  
              .showYAxis(true)
              .showXAxis(true)
;
 //Chart x-axis settings
chart.xAxis  
    .axisLabel('date')
    .tickFormat(function(d) {return new Date((data.Date - (25567 + 1))*86400*1000);

chart.yAxis     //Chart y-axis settings
    .axisLabel('close')
    .tickFormat(d3.scale.linear(data.Close));




d3.select('#Charts svg')    //Selecting the <svg> element where i want to render the chart in.   
    .datum(data)         //Populating the <svg> element with chart data...
    .call(chart);          //Finally, rendering the chart!

//Update the chart when window resizes.

  })

;

//数据 { “日期”:[13089、13094、13095、13096、13097、13098、13101、13103、13104、13105、13108、13109、13110] “关闭”:[ 2419.1、2461.6、2492.7、2489.1、2500.7、2548.7、2558.7、2582.8、2603.9、2620.1、2602.5、2572.8] }

最佳答案

与“Date”相比,“Close”中的数组元素数量较少。

以下是您可能正在寻找的可能解决方案:

    nv.addGraph(function () {
    var chart = nv.models.lineChart();

    chart.xAxis.axisLabel('date')
        .tickFormat(d3.format(''));

    chart.yAxis.axisLabel('close')
        .tickFormat(d3.format(''));

    d3.select('#dateChart')
        .datum(chartData())
        .transition().duration(500)
        .call(chart);

    nv.utils.windowResize(function () {
        d3.select('#dateChart').call(chart)
    });

    return chart;
});


function chartData() {
    var myData = {
        "Date": [13089, 13094, 13095, 13096, 13097, 13098, 13101, 13103, 13104, 13105, 13108, 13109, 13110],
        "Close": [2419.1, 2461.6, 2492.7, 2489.1, 2500.7, 2548.7, 2558.7, 2582.8, 2603.9, 2620.1, 2602.5, 2572.8, 2588.8]
        //The number of array elements in Close were less compared to Date. Hence added 2588.8 as the last element
    };

    var result = [];
    for (var i = 0; i < myData.Date.length; i++) {
        result.push({
            x: myData.Date[i],
            y: myData.Close[i]
        });
    }

    return [{
        values: result,
        key: 'Date Chart',
        color: '#ff7f0e'
    }];
}

JS fiddle :https://jsfiddle.net/m7oaxjue/3/

关于javascript - 如何将 JSON 数据添加到 nvd3 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33500848/

相关文章:

javascript - Setter/Getter 对此

javascript从flot绑定(bind)函数访问类对象

html - html5 中的 <picture> 元素是否会使 "alt"属性过时?

php - Ajax 实时搜索框

json - winston 日志格式

javascript - 如何在图像更改时暂停音频 onmouseout

java - 在 textarea 中禁用 Javascript 执行

javascript - 将图像从视频 JS 保存到 Canvas

javascript - 为什么这个表的最后一列太宽了?

javascript - 如何在 REACT js 中正确从 JSON 对象中删除特定项目?