D3.js - 如何使用内联JSON作为D3图表的数据集,而不是csv / tsv / json文件

时间:2017-04-26 13:32:42

标签: d3.js

我正在我的应用程序中实现D3.js图表​​,我不想将文件用作数据集,我只想使用内联JSON作为数据集(JSON将在应用程序中动态生成)。

我已使用以下代码完成Reusable Responsive Multiline Chart的实施。

var data1 = [ { "My JSON data here" } ];

d3.json('', function (error, data) {

    data1.forEach(function (d) {
        d.year = +d.year;
        d.variableA = +d.variableA;
        d.variableB = +d.variableB;
        d.variableC = +d.variableC;
        d.Temp = +d.Temp;
    });

    var chart = makeLineChart(data1, 'year', {
        'Device 1': { column: 'variableA' },
        'Device 2': { column: 'variableB' },
        'Device 3': { column: 'variableC' },
        'Device 4': { column: 'variableD' }
    }, { xAxis: 'Years', yAxis: 'Temperature' });
    chart.bind("#chart-line1");
    chart.render();
});

我在这里调用d3.json()但文件名为空,并且代码中还有不使用数据。而不是'数据',我正在使用'data1'。 效果很好......

现在我想为Grouped Bar Chart实现相同,但此图表数据绑定方法与“可重用响应多线图”不同。 以下是解析“Grouped Bar Chart”数据的代码。

d3.csv("\\data.csv", function(d, i, columns) {
  for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]];
  return d;
}, function(error, data) {
  if (error) throw error;

  var keys = data.columns.slice(1); 

  // Rest of code to bind parsed data to chart   
});

Grouped Bar Chart

处的完整代码

所以我可以在这里用内联JSON替换 data.csv

1 个答案:

答案 0 :(得分:2)

方法d3.jsond3.csv是用于从服务器获取数据的AJAX调用。如果您有内联JSON,则不需要这些调用。你的第一个例子就是这样的事实只是一个副作用。您的d3.json电话失败,但仍然会执行回叫功能。它只是不必要的,应该写成:

var data1 = [ { "My JSON data here" } ];

data1.forEach(function (d) {
    d.year = +d.year;
    d.variableA = +d.variableA;
    d.variableB = +d.variableB;
    d.variableC = +d.variableC;
    d.Temp = +d.Temp;
});

var chart = makeLineChart(data1, 'year', {
    'Device 1': { column: 'variableA' },
    'Device 2': { column: 'variableB' },
    'Device 3': { column: 'variableC' },
    'Device 4': { column: 'variableD' }
}, { xAxis: 'Years', yAxis: 'Temperature' });
chart.bind("#chart-line1");
chart.render();

再次在第二张图表上,无需拨打d3.csv。但是,从CSV格式到JSON会发生一些处理。您需要在创建JSON时复制它,并且要使图表的其余部分工作,您需要以下内容:

...

var z = d3.scaleOrdinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var data = [{"State":"CA","Under 5 Years":2704659,"5 to 13 Years":4499890,"14 to 17 Years":2159981,"18 to 24 Years":3853788,"25 to 44 Years":10604510,"45 to 64 Years":8819342,"65 Years and Over":4114496},{"State":"TX","Under 5 Years":2027307,"5 to 13 Years":3277946,"14 to 17 Years":1420518,"18 to 24 Years":2454721,"25 to 44 Years":7017731,"45 to 64 Years":5656528,"65 Years and Over":2472223}];

var keys = ["Under 5 Years", "5 to 13 Years", "14 to 17 Years", "18 to 24 Years", "25 to 44 Years", "45 to 64 Years", "65 Years and Over"]

x0.domain(data.map(function(d) { return d.State; }));
x1.domain(keys).rangeRound([0, x0.bandwidth()]);

...

以下代码运行而不调用d3.csv

&#13;
&#13;
<!DOCTYPE html>
<style>

.axis .domain {
  display: none;
}

</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x0 = d3.scaleBand()
    .rangeRound([0, width])
    .paddingInner(0.1);

var x1 = d3.scaleBand()
    .padding(0.05);

var y = d3.scaleLinear()
    .rangeRound([height, 0]);

var z = d3.scaleOrdinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var data = [{"State":"CA","Under 5 Years":2704659,"5 to 13 Years":4499890,"14 to 17 Years":2159981,"18 to 24 Years":3853788,"25 to 44 Years":10604510,"45 to 64 Years":8819342,"65 Years and Over":4114496},{"State":"TX","Under 5 Years":2027307,"5 to 13 Years":3277946,"14 to 17 Years":1420518,"18 to 24 Years":2454721,"25 to 44 Years":7017731,"45 to 64 Years":5656528,"65 Years and Over":2472223},{"State":"NY","Under 5 Years":1208495,"5 to 13 Years":2141490,"14 to 17 Years":1058031,"18 to 24 Years":1999120,"25 to 44 Years":5355235,"45 to 64 Years":5120254,"65 Years and Over":2607672},{"State":"FL","Under 5 Years":1140516,"5 to 13 Years":1938695,"14 to 17 Years":925060,"18 to 24 Years":1607297,"25 to 44 Years":4782119,"45 to 64 Years":4746856,"65 Years and Over":3187797},{"State":"IL","Under 5 Years":894368,"5 to 13 Years":1558919,"14 to 17 Years":725973,"18 to 24 Years":1311479,"25 to 44 Years":3596343,"45 to 64 Years":3239173,"65 Years and Over":1575308},{"State":"PA","Under 5 Years":737462,"5 to 13 Years":1345341,"14 to 17 Years":679201,"18 to 24 Years":1203944,"25 to 44 Years":3157759,"45 to 64 Years":3414001,"65 Years and Over":1910571}];

var keys = ["Under 5 Years", "5 to 13 Years", "14 to 17 Years", "18 to 24 Years", "25 to 44 Years", "45 to 64 Years", "65 Years and Over"];

  x0.domain(data.map(function(d) { return d.State; }));
  x1.domain(keys).rangeRound([0, x0.bandwidth()]);
  y.domain([0, d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();

  g.append("g")
    .selectAll("g")
    .data(data)
    .enter().append("g")
      .attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; })
    .selectAll("rect")
    .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
    .enter().append("rect")
      .attr("x", function(d) { return x1(d.key); })
      .attr("y", function(d) { return y(d.value); })
      .attr("width", x1.bandwidth())
      .attr("height", function(d) { return height - y(d.value); })
      .attr("fill", function(d) { return z(d.key); });

  g.append("g")
      .attr("class", "axis")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x0));

  g.append("g")
      .attr("class", "axis")
      .call(d3.axisLeft(y).ticks(null, "s"))
    .append("text")
      .attr("x", 2)
      .attr("y", y(y.ticks().pop()) + 0.5)
      .attr("dy", "0.32em")
      .attr("fill", "#000")
      .attr("font-weight", "bold")
      .attr("text-anchor", "start")
      .text("Population");

  var legend = g.append("g")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
      .attr("text-anchor", "end")
    .selectAll("g")
    .data(keys.slice().reverse())
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 19)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", z);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9.5)
      .attr("dy", "0.32em")
      .text(function(d) { return d; });

</script>
&#13;
&#13;
&#13;