简单的D3折线图示例

4
我是一名D3新手,在学习这个库的过程中进度缓慢。我试图让这个简单的D3面积图工作起来,但是在显示实际区域方面遇到了一些麻烦。我可以正确地显示轴,并且数据的范围也是正确的,但是图表本身没有显示任何区域。
我正在使用像这样的JSON数据,并且据我所知,它似乎可以正确处理数据。
[{"Date":"Date","Close":"Close"},{"Date":"20130125","Close":"75.03"},{"Date":"20130124","Close":"75.32"},{"Date":"20130123","Close":"74.29"},{"Date":"20130122","Close":"74.16"},{"Date":"20130118","Close":"75.04"},{"Date":"20130117","Close":"75.26"},{"Date":"20130116","Close":"74.34"},{"Date":"20130115","Close":"76.94"},{"Date":"20130114","Close":"76.55"}]

这是我的代码

    var margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

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

    var x = d3.time.scale()
        .range([0, width]);

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

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var area = d3.svg.area()
        .x(function(d) { return x(d.Date); })
        .y0(height)
        .y1(function(d) { return y(d.Close); });

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.json('JSONstockPriceOverTime.php', function (data) {
      data.forEach(function(d) {
        d.Date = parseDate(d.Date);
        d.Close = +d.Close;
      });

    x.domain(d3.extent(data, function(d) { return d.Date; }));
    y.domain([0, d3.max(data, function(d) { return d.Close; })]);

    svg.append("path")
      .datum(data)
      .attr("class", "area")
      .attr("d", area);

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

    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Price ($)");
    });

我已经应用了这个样式

        <style>

        body {
          font: 10px sans-serif;
        }

        .axis path,
        .axis line {
          fill: none;
          stroke: #000;
          shape-rendering: crispEdges;
        }

        .area {
          fill: steelblue;
        }


    </style>
1个回答

4

移除json (JSONstockPriceOverTime.php)文件的开头部分;

{"Date":"日期","Close":"收盘价"},

由于'日期'和'收盘价'被作为json格式的一部分定义了,因此您不需要像csv文件那样包含标题信息,并将'error'添加到您的json加载行中。

d3.json("JSONstockPriceOverTime.php", function(error, data) {

这样就可以了(对我有效)。

您正在取得良好的进展。


2
没问题。祝你好运。根据你的水平,你可能会对D3技巧和技巧手册感兴趣(反正它是免费的!)或d3noob.org上的其他类似代码示例感兴趣。 - d3noob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接