在D3 Javascript可视化中使用JSON数据

Using JSON data in D3 Javascript visualisation

本文关键字:JSON 数据 D3 Javascript 可视化      更新时间:2023-09-26

我正在使用JSON数据来驱动使用javascript D3可视化工具(http://mbostock.github.com/d3/)制作的一些图表。我已经设置了我的WCF服务,这段代码在Jquery中工作得很好:

$('#getDataItems').click(function () {
            var $DataList = $('#DataList');
            $DataList.empty().appendLi('Loading...');
            // Get the JsonP data
            $.getJSON('http://localhost:65025/CustomersService.svc/GetMyDataItems?callback=?', null, function (somedata) {
                alert('Received ' + somedata.length + ' Items');
                $DataList.empty();
                $.each(somedata, function () {
                    $DataList.appendLi(this.ID + " - " + this.Value);
                });  // end each dataitem function
            });  // end success function
        });  // end #getDataItems.click

D3也有使用JSON数据的功能,但我还没有成功。它看起来像这样:

// this works
//var data = [4, 8, 15, 16, 23, 42];
// this doesn't
     var data = function () {
            d3.json('http://localhost:65025/CustomersService.svc/GetMyDataItems?callback=?',
     function (data) }  })
   }
//.. rest of the example is known working code so its here only for reference
// create the chart class as an append to the body element.
var chart = d3.select("body")
    .append("svg:svg")
    .attr("class", "chart")
    .attr("width", 420)
    .attr("height", 20 * data.length);
// Set the width relative to max data value
var x = d3.scale.linear()
 .domain([0, d3.max(data)])
 .range([0, 420]);
var y = d3.scale.ordinal()
 .domain(data)
 .rangeBands([0, 120]);
chart.selectAll("rect")
 .data(data)
 .enter().append("svg:rect")
 .attr("y", y)
 .attr("width", x)
 .attr("height", y.rangeBand());
chart.selectAll("text")
 .data(data)
 .enter().append("svg:text")
 .attr("x", x)
 .attr("y", function (d) { return y(d) + y.rangeBand() / 2; })
 .attr("dx", -3) // padding-right
 .attr("dy", ".35em") // vertical-align: middle
 .attr("text-anchor", "end") // text-align: right
 .text(String);

几乎所有的代码都来自D3下载中的"条形图"示例,它工作得很好。如果我手动声明数据(根据上面的整数数组),它可以工作,但不能使用JSON命令。我还简化了返回的数据,使其仅由整数组成。最终,我希望能够访问JSON数据与'id字段','值字段'等,并在代码中引用这些。

有人知道我的语法是否不正确吗?我意识到函数(data)是用来向图表中添加数据的,但是这个例子中的代码可以工作,所以我更愿意从那个点开始。

D3有自己的json获取功能的完整性框架,但你不必使用它。你可以尝试你的d3图表与jQuery $.getJSON,它应该工作。这就是我所做的,因为我的大部分开发都是使用jQuery完成的。

对于您的示例,d3.json语义与$.getJSON完全相同。这是一种异步调用,其中在检索到数据后调用函数。试试这样做:

d3.json(
  'http://localhost:65025/CustomersService.svc/GetMyDataItems?callback=?',
  function (jsondata) {
    // create the chart here with
    // the returned data
    console.log(jsondata);
    var data = jsondata.map(function(d) { return d.Value; });
    console.log(data);
  });