gpt4 book ai didi

javascript - 向我的条形图添加条件格式时出现 TypeError/Undefined

转载 作者:行者123 更新时间:2023-11-30 21:01:39 25 4
gpt4 key购买 nike

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

TypeError: c[(this.position + "Field")] 未定义

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

最佳答案

出现这个错误是因为这个字符串:

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

看起来您重写了该库在后台设置的数据绑定(bind)。我没有使用 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>

关于javascript - 向我的条形图添加条件格式时出现 TypeError/Undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47079512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com