【问题标题】:Graph not rendering my Date data图表未呈现我的日期数据
【发布时间】:2016-03-09 07:22:12
【问题描述】:

使用 javascript,D3.js,这是我第一次处理 D3。我开始使用一个工作示例,但现在它不起作用: My Graph 这是javascript代码:

//************************************************************
// Data notice the structure
//************************************************************
var data =  [
    [
     {'x':'01/01/2016','y':0},{'x':'01/02/2016','y':5},
     {'x':'01/03/2016','y':1},{'x':'01/04/2016','y':0},
     {'x':'01/05/2016','y':6},{'x':'01/06/2016','y':1},
     {'x':'01/07/2016','y':5}
    ],
    [
     {'x':'01/01/2016','y':1},{'x':'01/02/2016','y':6},
     {'x':'01/03/2016','y':2},{'x':'01/04/2016','y':1},
     {'x':'01/05/2016','y':7},{'x':'01/06/2016','y':2},
     {'x':'01/07/2016','y':6}
    ]
    [
     {'x':'01/01/2016','y':2},{'x':'01/02/2016','y':7},
     {'x':'01/03/2016','y':3},{'x':'01/04/2016','y':2},
     {'x':'01/05/2016','y':5},{'x':'01/06/2016','y':3},
     {'x':'01/07/2016','y':7}
    ]
];

var colors = [
    'steelblue',
    'green',
    'red'
]

var minDate = data[0][0].x;
var len = data[0].length;
var maxDate = data[0][len - 1].x;
console.log("minDate: "+minDate);
console.log("maxDate: "+maxDate);
//************************************************************
// Create Margins and Axis and hook our zoom function
//************************************************************
var margin = {top: 20, right: 30, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.time.scale()
    .domain([new Date(minDate), new Date(maxDate)])
    // .domain([ 0, 12 ])
    .range([0, width]);

var y = d3.scale.linear()
    .domain([-1, 16])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
  .ticks(5) // fixes the duplicate date issue until zooming in enough
    .tickSize(-height)
    .tickPadding(10)    
    .tickSubdivide(true)    
  .tickFormat(d3.time.format("%x"))

    .orient("bottom");  

var yAxis = d3.svg.axis()
    .scale(y)
    .tickPadding(10)
    .tickSize(-width)
    .tickSubdivide(true)    
    .orient("left");

var zoom = d3.behavior.zoom()
    .x(x)
    .scaleExtent([1, 10])
    .on("zoom", zoomed);    

//************************************************************
// Generate our SVG object
//************************************************************  
var svg = d3.select("body").append("svg")
    .call(zoom)
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

svg.append("g")
    .attr("class", "y axis")
    .append("text")
    .attr("class", "axis-label")
    .attr("transform", "rotate(-90)")
    .attr("y", (-margin.left) + 10)
    .attr("x", -height/2)
    .text('Bullshit');  

svg.append("clipPath")
    .attr("id", "clip")
    .append("rect")
    .attr("width", width)
    .attr("height", height);


// svg.xAxis
//   .tickFormat(function(d) {
//     return d3.time.format("%m/%d/%Y")(new Date(d));
// })

// svg.xScale(d3.time.scale());
//************************************************************
// Create D3 line object and draw data on our SVG object
//************************************************************
var line = d3.svg.line()
    .interpolate("linear")  
    .x(function(d) { return x(d.x); })
    .y(function(d) { return y(d.y); });     

svg.selectAll('.line')
    .data(data)
    .enter()
    .append("path")
    .attr("class", "line")
    .attr("clip-path", "url(#clip)")
    .attr('stroke', function(d,i){          
        return colors[i%colors.length];
    })
    .attr("d", line);       




//************************************************************
// Draw points on SVG object based on the data given
//************************************************************
var points = svg.selectAll('.dots')
    .data(data)
    .enter()
    .append("g")
    .attr("class", "dots")
    .attr("clip-path", "url(#clip)");   

points.selectAll('.dot')
    .data(function(d, index){       
        var a = [];
        d.forEach(function(point,i){
            a.push({'index': index, 'point': point});
        });     
        return a;
    })
    .enter()
    .append('circle')
    .attr('class','dot')
    .attr("r", 2.5)
    .attr('fill', function(d,i){    
        return colors[d.index%colors.length];
    })  
    .attr("transform", function(d) { 
        return "translate(" + x(d.point.x) + "," + y(d.point.y) + ")"; }
    );






//************************************************************
// Zoom specific updates
//************************************************************
function zoomed() {
    svg.select(".x.axis").call(xAxis);
    // svg.select(".y.axis").call(yAxis);   
    svg.selectAll('path.line').attr('d', line);  

    points.selectAll('circle').attr("transform", function(d) { 
        return "translate(" + x(d.point.x) + "," + y(d.point.y) + ")"; }
    );  
}

所以我试图在帖子顶部呈现示例数据。我的最终目标是制作一个包含三个绘制线的图表,这些线在每个 x,y 坐标处都有点,就像这个图表:Original Graph

再一次,我对 D3 不是很有经验,我尝试寻找示例(我找到了一些示例),但我仍然无法让我的图表显示我的线条。现在,如果您检查我图表上的控制台,我会遇到以下错误:

错误:属性 d="MNaN 的值无效, 423.52941176470586LNaN, 291.17647058823525LNaN, 397.05882352941177LNaN, 423.52941176470586LNaN, 264.70588235294116LNaN, 397.05882352941177LNaN, 291.17647058823525"

未捕获的类型错误:无法读取未定义的属性“长度”

我自己的结论可能很模糊,告诉我我没有正确解析数据。

我应该补充一点,如果放大,图表会显示重复的日期,我不确定这是否可能是问题;也许图表对绘制哪个数据点感到困惑? (顺便说一下,重复的日期是另一个问题)

【问题讨论】:

    标签: javascript d3.js graph


    【解决方案1】:

    您应该使用日期格式化程序将 x ('01/01/2016') 中的字符串转换为日期:

    var format = d3.time.format("%m/%d/%Y");
    

    并使用此格式化程序将您的日期转换为日期对象。

    var x = d3.time.scale()
      .domain([format.parse(minDate), format.parse(maxDate)])
    

    在行函数中也有相同的格式化程序

    var line = d3.svg.line()
      .interpolate("linear")
      .x(function(d) {
        return x(format.parse(d.x));//convert into date
      })
      .y(function(d) {
        return y(d.y);
      });
    

    工作示例here

    【讨论】:

    • 嗯。我觉得荒谬。我几乎可以肯定我试过了!谢谢!不过有一件事,我注意到控制台正在打印 的错误。你知道为什么不处理数据点来渲染图表上的点吗?
    • Nothing new 同样的错误 :) 应该是 x(format.parse(d.point.x)) 将其转换为日期更正的小提琴 codepen.io/anon/pen/oxxwMe?editors=0010
    • 哇。我想那时我要学习D3还有很长的路要走。再次感谢您的帮助;与这个问题一样荒谬的是,我实际上至少花了一天左右的时间试图弄清楚为什么它不起作用!
    【解决方案2】:

    d3.time.scale 函数接受一个 javascript 日期对象。

    在你的 line 函数中,你输入一个日期字符串。您需要先将日期字符串解析为 javascript 日期对象,然后再将其传递给函数。

    var line = d3.svg.line()
      .interpolate("linear")
      .x(function(d) {
    
        return x(new Date(d.x));
        console.log(d.x, x(new Date(d.x))); // x(new Date(d.x)) now doesn't return NAN =]
      })
      .y(function(d) {
        return y(d.y);
      });
    

    【讨论】:

    • 糟糕!我首先看到其他人的回应,我不知道我是如何滚动浏览这个的。我试过你的例子,它也有效!谢谢!但是,我确实有和@Cyril 一样的问题,你知道为什么不再绘制图表上的点吗??
    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 2018-11-20
    • 2020-12-19
    • 1970-01-01
    • 2017-06-04
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多