TypeError/Undefined 向我的条形图添加条件格式时

TypeError/Undefined when adding conditional formatting to my bar chart

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

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>

当前结果:

由于这个字符串出现这个错误:

...
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()方法,您可以通过索引获取相应的数据项。看看下面隐藏的代码片段,它有效:

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";
        });
<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>