我可以将日期字符串直接传递给d3条形图数据吗?

时间:2016-06-23 10:02:45

标签: javascript jquery json d3.js

我尝试使用d3 js构建stackedBarChart,但每当我将数据传递给变量时,它在图表div上都不显示

下面是我的jquery代码:

var stackedBarChartData = [{key:"Facebook","color":"#348fe2",value:[{x:"2016-06-13",y:7},{x:"2016-06-14",y:0},{x:"2016-06-15",y:0},{x:"2016-06-16",y:0},{x:"2016-06-17",y:2},{x:"2016-06-18",y:0},{x:"2016-06-19",y:1},{x:"2016-06-20"
            ,y:4},{x:"2016-06-21",y:4},{x:"2016-06-22",y:0},{x:"2016-06-23",y:0}]},{key:"Twitter","color":"#00acac"
            ,value:[{x:"2016-06-13",y:0},{x:"2016-06-14",y:0},{x:"2016-06-15",y:0},{x:"2016-06-16",y:0},{x:"2016-06-17"
            ,y:0},{x:"2016-06-18",y:0},{x:"2016-06-19",y:0},{x:"2016-06-20",y:0},{x:"2016-06-21",y:0},{x:"2016-06-22"
            ,y:0},{x:"2016-06-23",y:0}]},{key:"Whatsapp","color":"#33bdbd",value:[{x:"2016-06-13",y:0},{x:"2016-06-14"
            ,y:0},{x:"2016-06-15",y:0},{x:"2016-06-16",y:0},{x:"2016-06-17",y:0},{x:"2016-06-18",y:0},{x:"2016-06-19"
            ,y:0},{x:"2016-06-20",y:0},{x:"2016-06-21",y:0},{x:"2016-06-22",y:0},{x:"2016-06-23",y:0}]},{key:"Message"
            ,"color":"#c47d15",value:[{x:"2016-06-13",y:0},{x:"2016-06-14",y:0},{x:"2016-06-15",y:0},{x:"2016-06-16"
            ,y:0},{x:"2016-06-17",y:0},{x:"2016-06-18",y:0},{x:"2016-06-19",y:0},{x:"2016-06-20",y:0},{x:"2016-06-21"
            ,y:0},{x:"2016-06-22",y:1},{x:"2016-06-23",y:0}]},{key:"Email","color":"#ff5b57",value:[{x:"2016-06-13"
            ,y:0},{x:"2016-06-14",y:0},{x:"2016-06-15",y:0},{x:"2016-06-16",y:0},{x:"2016-06-17",y:0},{x:"2016-06-18"
            ,y:0},{x:"2016-06-19",y:0},{x:"2016-06-20",y:1},{x:"2016-06-21",y:3},{x:"2016-06-22",y:1},{x:"2016-06-23"
            ,y:0}]}];

                nv.addGraph({
                    generate: function() {
                        var stackedBarChart = nv.models.multiBarChart()
                            .stacked(true)
                            .showControls(false);

                        var svg = d3.select('#nv-bar-chart-sharing').append('svg').datum(stackedBarChartData);
                        svg.transition().duration(0).call(stackedBarChart);
                        return stackedBarChart;
                    }
                });



  <div id="nv-bar-chart-sharing" class="height-400"></div>

我已经有一个stackedBarChart的例子,其中json值包含“value”键中的所有整数数据但是这里我为x轴传递了日期所以我可以在那里通过日期吗?如果否,那么如何在x轴上显示日期

1 个答案:

答案 0 :(得分:1)

为此你需要告诉nvd3期望在x:

中的日期
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

现在以这种格式显示节目

var stackedBarChart = nv.models.multiBarChart()
  .stacked(true)
  .showControls(false)
  .x(function (d){
  return new Date(d.x);//this will get the date
})

工作代码here