我想通过单选按钮选择一个值时更新我的条形图。此值作为我的查询的参数传递以获取相应的JSON数据。如何重新绘制D3条形图
该代码工作正常,排除一个方面。当我通过单击任何单选按钮来选择一个值时,条形图将绘制在现有条形图的顶部。我希望每次选择新选项时都要重新绘制图表。
// set the dimensions of the canvas
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// set the ranges
var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
var y = d3.scale.linear().range([height, 0]);
// define the axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
var compSvg = d3.select(".company");
var companies = [];
d3.json("http://localhost:8983/solr/techproducts/select?q=popularity:[10%20TO%20*]&wt=json&fl=cat&facet=true&facet.field=cat", function(error, resp) {
var results = resp.facet_counts.facet_fields.cat;
for (var i = 0; i < 5; i++) {
var value = results[i*2];
companies.push(value);
}
});
//functions for toggling between data
function change(value){
update(value);
}
function update(comp){
var query = 'cat:"' + comp + '"';
var url = "http://localhost:8983/solr/techproducts/select?q=" + encodeURIComponent(query) + "&rows=10&fl=manu,price&wt=json"
// load the data
d3.json(url, function(error, resp) {
if (error) return console.error(error);
resp.response.docs.forEach(function(d) {
d.manu = d.manu;
d.price = +d.price;
});
// scale the range of the data
x.domain(resp.response.docs.map(function(d) { return d.manu; }));
y.domain([0, d3.max(resp.response.docs, function(d) { return d.price; })]);
// add axis
compSvg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)");
compSvg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 5)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price");
// Add bar chart
compSvg.selectAll("bar")
.data(resp.response.docs)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.manu); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.price); })
.attr("height", function(d) { return height - y(d.price); });
});
}
您是否尝试过'd3.selectAll( “酒吧”),删除();'并把它作为调用的第一个项目。? –
'compSvg.selectAll(“bar”)'总是会给你一个空的选择,因此在设置数据后,输入选择将总是追加新的矩形。尝试:'compSvg.selectAll(“.bar”) - 您正在将'rect'元素附加到'bar'类,而不是'bar'元素。 –
@AndrewReid这是一个改进,但它没有什么区别:OP只有一个“输入”选择,没有更新或退出选择。这是他/她的问题。 –