我正在努力从选择过滤器中更新d3.js图表。一切都会在第一次运行时运行并加载数据,但是,当选择过滤器并且第二次运行update元素时,update函数中的console.log(data)返回未定义。我已经搜索过,但我不明白为什么会这样?我的想法是,我将能够添加以下内容以过滤数据,然后添加新的数据元素并删除旧的数据元素。我已经剥离了所有内容以尝试了解发生了什么,但是我已经到了可以发现错误的地步:
var data = data.filter(function(d){
if (survey == "all") { return true; }
else {
return d.name == survey;
}
})
数据采用非常基本的格式,与选择下拉列表匹配。
名称,值
var margin = {top: 10, right: 10, bottom: 100, left:200}
var width = 1000 - margin.left - margin.right,
height = 700 - margin.top - margin.bottom;
var svg = d3.select("#graphic_two").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var time = 0;
var data;
// Set the X Label
var xLabel = g.append("text")
.attr("class", "x label")
.attr("y", height + 50)
.attr("x", width / 2)
.attr("font-size", "15px")
.attr("text-anchor", "middle")
.text("Topic Count");
// Set the Y Label
var yLabel = g.append("text")
.attr("class", "y axisLabel")
.attr("transform", "rotate(-90)")
.attr("y", -(120))
.attr("x", -350)
.attr("font-size", "15px")
.attr("text-anchor", "middle")
.text("Topic Names")
d3.json(topicData).then(function(data){
//console.log(data);
update(data)
})
$("#survey")
.on("change", function(){
update(data);
})
function step(){
// At the end of our data, loop back
time = (time < 214) ? time+1 : 0
update(data);
}
function update(data) {
console.log("I'm in the update function")
var survey = $("#survey").val();
console.log(survey);
console.log(data)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<select id="survey" data-placeholder="Select a survey type..." class="chosen-select" style="width:350px;" tabindex="3">
<option selected value="all">All</option>
<option value="Vehicle - Poor">Vehicle - Poor</option>
<option value="Problems - Unresolved">Problems - Unresolved</option>
<option value="Reliability - Poor">Reliability - Poor</option>
</select>
<div id="graphic_two"></div>