我正在尝试更新下拉列表选择更改的条形图。当我更改选择时,新条形图会附加在现有图表的底部。如何更新现有条形图或删除现有条形图并添加新条形图。我是D3 javascript的新手,需要一些帮助。我已经看过关于堆栈溢出和其他资源的其他类似问题,但它们不知何故不起作用。请看代码:
<script>
var data = {{ value|safe }}
function MyGraph(obj) {
var selectVal = String(obj[obj.selectedIndex].value);
var width = 1160, height = 400;
var margin = {top: 50, right: 50, bottom: 50, left: 50};
//x and y Scales
var xScale = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var yScale = d3.scale.linear()
.range([height, 0]);
xScale.domain(data.map(function(d) { return d.provider_name; }));
yScale.domain([0, d3.max(data, function(d) {
if(selectVal =="average_coverage"){
return d.average_coverage;
}
else if(selectVal=="average_total_charges"){
return d.average_total_charges;
}
else{
return d.average_medicare_payments;
}
})]);
//x and y Axes
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(25, "$");
//create svg container
var svg = d3.select("#graph")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
xScale.domain(data.map(function(d) { return d.provider_name; }));
yScale.domain([0, d3.max(data, function(d) {
if(selectVal =="average_coverage"){
return d.average_coverage;
}
else if(selectVal=="average_total_charges"){
return d.average_total_charges;
}
else{
return d.average_medicare_payments;
}
})]);
//create bars
var bars = svg.selectAll("bar")
.data(data);
bars.enter()
.append("rect")
//.attr("y",innerHeight)
.attr("height",0)
.attr("class", "bar");
bars.exit().remove();
bars.transition()
.duration(700)
.ease("linear")
.attr("x",function(d) { return xScale(d.provider_name); })
.attr("width", xScale.rangeBand())
.attr("y", function(d) {
if(selectVal =="average_coverage"){
return yScale(d.average_coverage);
}
else if(selectVal=="average_total_charges"){
return yScale(d.average_total_charges);
}
else{
return yScale(d.average_medicare_payments);
}
})
.attr("height", function(d) {
if(selectVal =="average_coverage"){
return height - yScale(d.average_coverage);
}
else if(selectVal=="average_total_charges"){
return height - yScale(d.average_total_charges);
}else{
return height-yScale(d.average_medicare_payments);
}
})
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
//drawing the x axis on svg
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
//drawing the y axis on svg
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Average Cost");
};