在条形图中添加条件格式时,TypeError / Undefined

时间:2017-11-02 15:53:28

标签: javascript d3.js dimple.js

我正在尝试将条件格式添加到我的简单条形图中。它部分工作,直到我试图悬停其中一个条,然后我得到以下错误:

TypeError: c[(this.position + "Field")] is undefined

data.csv的内容:

date,est_sleep,bool_field
2017-11-01,7.5,0
2017-10-31,8,0
2017-10-30,7,1

HTML代码:

<div id="chartContainer">
  <script type="text/javascript">
    d3.csv("data.csv", function(data) {
        var svg = dimple.newSvg("#chartContainer", 500, 600);

        var myChart = new dimple.chart(svg, data);
        myChart.setBounds(60, 30, 400, 300)
        myChart.addCategoryAxis("x", "date");
        var y = myChart.addMeasureAxis("y", "est_sleep");
        var x = myChart.addSeries(null, dimple.plot.bar);
        x.addOrderRule("date", true);
        myChart.draw();

        svg.selectAll('rect')
        .data(data)
        .style("fill", function(d){
            if(d.bool_field == 1)
                return "#f00";
            else
                return "#99C1DC";
        })
        .style("stroke", function(d){
            if(d.bool_field == 1)
                return "#931D1D";
            else
                return "#98B5C9";
        });
    });
  </script>
</div>

目前的结果:

enter image description here

1 个答案:

答案 0 :(得分:1)

由于此字符串而出现此错误:

...
svg.selectAll('rect')
  .data(data) // <== !!!
...

看起来你重写了这个库设置的数据绑定。我没有使用dimple.js,也许存在更优雅的解决方案,但我可以建议你这个解决方案:

svg.selectAll('rect')
  .style("fill", function(d,i){
    if(data[i].bool_field == 1) // <== get data item by index
      return "#f00";
    else
      return "#99C1DC";
  })
  .style("stroke", function(d,i){
    if(data[i].bool_field == 1) // <== get data item by index
      return "#931D1D";
    else
      return "#98B5C9";
  });

您可以按索引获取相应的数据项,而不使用.data()方法。查看下面隐藏的代码段,它可以工作:

&#13;
&#13;
data = d3.csvParse(`date,est_sleep,bool_field
2017-11-01,7.5,0
2017-10-31,8,0
2017-10-30,7,1`);

var svg = window.dimple.newSvg("#chartContainer", 500, 600);

        var myChart = new dimple.chart(svg, data);
        myChart.setBounds(60, 30, 400, 300)
        myChart.addCategoryAxis("x", "date");
        var y = myChart.addMeasureAxis("y", "est_sleep");
        var x = myChart.addSeries(null, dimple.plot.bar);
        x.addOrderRule("date", true);
        
        myChart.draw();

        svg.selectAll('rect')
        .style("fill", function(d,i){
            if(data[i].bool_field == 1)
                return "#f00";
            else
                return "#99C1DC";
        })
        .style("stroke", function(d,i){
            if(data[i].bool_field == 1)
                return "#931D1D";
            else
                return "#98B5C9";
        });
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
<div id="chartContainer"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dimple/2.3.0/dimple.latest.min.js"></script>
&#13;
&#13;
&#13;