我有一个下拉菜单项,每个选定的下拉菜单项都有不同的csv文件来显示单词云(单词,频率)。您可以在下面找到代码。当我选择一个项目时,会显示一个词云,但是当我选择下一个项目时,也会显示另一个词云,而不会清除前一个词云。我只想显示一个词云,它是下拉列表中最近单击的词云。我尝试使用.exit()。remove(),但它似乎无法正常工作,因为词云仍然连续出现word-cloud-image。我要先谢谢你。
var margin = {top: 40, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body").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 + ")");
var allGroup = ["Jose", "Thomas"]
d3.select("#selectButton")
.selectAll('myOptions')
.data(allGroup)
.enter()
.append('option')
.text(function (d) { return d; }) // text showed in the menu
.attr("value", function (d) { return d; }) // corresponding value returned by the button
var fill = d3.scale.category20();
d3.csv("words.csv", function(d) {
return {
text: d.word,
size: +d.freq/6
}
},
function(data) {
d3.layout.cloud().size([width, height]).words(data)
//.rotate(function() { return ~~(Math.random() * 2) * 90; })
.rotate(0)
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
function updateAilments(){
d3.csv("data1.csv", function(d) {
return {
text: d.ailment_name,
size: +d.frequency/2
}
},
function(data) {
d3.layout.cloud().size([width, height]).words(data)
//.rotate(function() { return ~~(Math.random() * 2) * 90; })
.rotate(0)
.font("Impact")
.fontSize(function(d) { return d.size; })
.text(function(d) { return d.text; })
.on("end", draw)
.start();
})
}
function draw(words) {
var svg = d3.select("#cloud").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")")
.selectAll("text")
.data(words)
var contentEnter = svg.enter().append("text");
contentEnter
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; })
svg.exit().remove();
}
d3.select("#selectButton").on("change", function(d) {
// recover the option that has been chosen
var selectedOption = d3.select(this).property("value")
// run the updateChart function with this selected option
switch (selectedOption)
{
case "Thomas":
updateAilments(selectedOption)
break
default:
updateAilments(selectedOption)
}
})
});