D3.js数据组和转换

D3.js data groups and transitions

本文关键字:转换 数据 js D3      更新时间:2024-05-10

受Mike Bostock的《国富论》的启发,我试图说明感染率随时间的变化。我试图按Month分组,并沿着x轴(Month)传递()一个气泡。

我坚持按月份分组。。。

根据下面Lars和Christopher的有益反馈,我对这篇文章进行了重大编辑。

这里有一个jsFiddle示例-hhttp://jsfiddle.net/Nyquist212/JSsHL/1/

    <div id="chart"></div>
    <script type="text/javascript">
    var json = 
    [
      {
        "Month":1,
        "VisitCount":894,
        "DiagnosisName":"ACUTE PHARYNGITIS"
      },
      {
        "Month":1,
        "VisitCount":807,
        "DiagnosisName":"PNEUMONIA ORGANISM NOS"
      },
      {
        "Month":2,
        "VisitCount":566,
        "DiagnosisName":"ACUTE PHARYNGITIS"
      },
      {
        "Month":2,
        "VisitCount":456,
        "DiagnosisName":"PNEUMONIA ORGANISM NOS"
      },
      {
        "Month":3,
        "VisitCount":273,
        "DiagnosisName":"ACUTE PHARYNGITIS"
      },
      {
        "Month":3,
        "VisitCount":189,
        "DiagnosisName":"PNEUMONIA ORGANISM NOS"
      }
    ]
   var svgContainer = d3.select("#chart")
            .append("svg")
            .attr("height", 250)
            .attr("width",750);
    var bubbleGroup = svgContainer.append("g");
    var bubble =  bubbleGroup.selectAll("circle")
            .data(json)
            .enter()
            .append("circle");
    var bubbleAttributes = bubble
            .style("stroke", "blue")
            .style("fill", "white")
            .attr("r", function(d){return (d.VisitCount/10);})
            .attr("cy", 150)
            .attr("cx", function(d){return (d.Month * 100);});
    d3.select("Body").selectAll("p")
            .data(json)
            .enter()
            .append("p")
            .text(function(d){return d.Month + " " + d.DiagnosisName + " " + d.VisitCount;})
    </script>

编辑:更新Christopher Chiche 的更正

编辑:更新为Lars Kotthoff 建议的部分工作示例

我将使用d3.nest和转换循环的组合。举个例子:

svg.selectAll("circle")
    .data(d3.nest()
            .key(function(d) { return d.DiagnosisName; })
            .entries(json))
    .enter().append("circle")
    .style("stroke", "blue")
    .style("fill", "white")
    .attr("cy", 150)
    .attr("cx", 0)
    .attr("r", 0)
    .each(function(d) {
        for(var i = 0; i < d.values.length; i++) {
            d3.select(this).transition().delay(1000 * i).duration(1000)
              .attr("r", function(d){return (d.values[i].VisitCount/10);})
              .attr("cx", function(d){return (d.values[i].Month * 100);});
        }
    });

在这里完成jsfiddle。

您的问题是dataset不包含任何数据。它是对d3函数的调用,不返回任何内容。但是,您有一个csv变量,它作为参数传递给drawChart函数。

你应该这样写:

var circleGroup = svgContainer.append("g")
    .selectAll("circles")
    .data(csv)

每次在data()调用中使用"dataset"时也是如此。

如果没有数据,那么d3不会绘制任何内容。因此,当你遇到这种问题时,查看你所附的数据在大多数情况下都会有所帮助。

此外,由于同样的原因,interpolateData不起作用,您可能应该将data作为参数传递。