Animation 如何在D3气泡图的动画中使用JSON对象的元素更改属性

Animation 如何在D3气泡图的动画中使用JSON对象的元素更改属性,animation,d3.js,Animation,D3.js,我是D3新手。我制作了一个包含五个气泡的图表,其中“r”属性是通过一个名为“estudiantes”的JSON成员定义的。在同一图表中有一个按钮。当有人点击按钮时,我试图使“r”属性改变,并由另一个名为estudiantes2010的JSON成员定义,但它不起作用。如果我为“r”使用一个固定值,动画效果和气泡半径会发生变化,因此我猜我在将JSON对象绑定到r属性时出错了,但我不知道是什么原因。谢谢 代码如下: <!DOCTYPE html> <html lang="en">

我是D3新手。我制作了一个包含五个气泡的图表,其中“r”属性是通过一个名为“estudiantes”的JSON成员定义的。在同一图表中有一个按钮。当有人点击按钮时,我试图使“r”属性改变,并由另一个名为estudiantes2010的JSON成员定义,但它不起作用。如果我为“r”使用一个固定值,动画效果和气泡半径会发生变化,因此我猜我在将JSON对象绑定到r属性时出错了,但我不知道是什么原因。谢谢

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>D3 Test</title>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script type="text/javascript" src="data/carreras.json"></script>
</head>
<body>
     <script type="text/javascript">

          var w = 2000;
          var h = 500;

          var SVG = d3.select("body")
           .append("svg")
           .attr("width", w)
           .attr("height", h);    

          var circulos = SVG.selectAll("circle")
           .data(jsonCarreras2002)
           .enter().append("circle")
           .style("stroke", "gray")
           .style("fill", "white")
           .attr("r", function(d) {return Math.sqrt(d.estudiantes/20);})
           .attr("cx", function(d, i){return 30+(i*140+170)})
           .attr("cy", 250);

          var button = d3.select("body")
            .append("input")
            .attr("type","button")
            .attr("value", "A button");

          button.on("click", function() {
            circulos.transition()
           .attr("r", function(d) {return Math.sqrt(d.estudiantes2010/20);})
           });



    </script>
    </body> 
    </html> 

首先,我认为您在
json
中有一个输入错误,最后一行之前的
estudiante20103
应该是
estudiante2010

看看这个。在底部,我又添加了一个按钮,为所有圆圈设置常量值,只是为了好玩

玩一点按钮,你会发现两者都能工作。如果希望更彻底地测试,可以创建更多按钮

然后看看你的例子有什么问题,但无论如何你都有一个有效的解决方案

一个区别是,我将数据定义封装在函数
getData()
中,也可以尝试一下

如果你有时间,你也许可以看看其他有用的,甚至更复杂,但也很漂亮的例子

对我有用--
          var jsonCarreras2002 = [
            { "nombre": "Artes y Humanidades",
              "estudiantes": 29410,
              "estudiantes2010": 38767,
              "prueba": 20},
            { "nombre": "CC. Sociales y jurídicas",
              "estudiantes": 147482,
              "estudiantes2010": 140613,
              "prueba": 20},
              { "nombre": "Ciencias",
              "estudiantes": 18510,
              "estudiantes2010": 20189,
              "prueba": 20},
              { "nombre": "CC. De la Salud",
              "estudiantes": 22238,
              "estudiantes2010": 44636,
              "prueba": 20},
              { "nombre": "Ingeniería y Arquitectura",
              "estudiantes": 75947,
              "estudiantes20103": 59772,
              "prueba": 20}];