已尝试过多次以使其正常运行,但仍未更新,仅显示默认图表(阿富汗),请帮帮我。我可以确定的一件事是问题出在过滤器部分,但我不知道如何使过滤器一次又一次地反转。
// Read in data
d3.csv("data.csv").then(function (data) {
var allGroup = ['Afghanistan', 'Armenia', 'Australia', 'Austria', 'Azerbaijan',...(omit) ];
var dropdownButton = d3.select("#selectButton")
.append('select')
.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
updateChart(allGroup[0])
function updateChart(country) {
// Filter the data to only include a single metric
var subset = data.filter(function (el) { return el.country_region === allGroup[0]; });
// Set the color domain equal to the three product categories
var productCategories = d3.keys(data[0]).filter(function (key) {
return key == "happiness_score" || key == "life_expectancy" || key == "economy";
});
color5.domain(productCategories);
// Format the data field
data.forEach(function (d) {
d.year = parseTime5(d.year)
});
// Reformat data to make it more copasetic for d3
// data = An array of objects
// concentrations = An array of three objects, each of which contains an array of objects
var concentrations = productCategories.map(function (category) {
return {
category: category,
datapoints: subset.map(function (d) {
return {year: d["year"], concentration: +d[category]};
})
};
});
// console.log(JSON.stringify(concentrations, null, 2)) // to view the structure
// Set the domain of the axes
xScale5.domain(
d3.extent(subset, function (d) {
return d["year"];
})
);
yScale5.domain([0, 8]);
// Place the axes on the chart
svg5
.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis5);
svg5
.append("g")
.attr("class", "y axis")
.call(yAxis5)
.append("text")
.attr("fill", "black")
.attr("transform", "translate(30,-10)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Score");
var products = svg5
.selectAll(".category")
.data(concentrations)
.enter()
.append("g")
.attr("class", "category");
products
.append("path")
.attr("class", "line")
.attr("d", function (d) {
return line5(d.datapoints);
})
.style("stroke", function (d) {
return color5(d.category);
})
products
.transition()
.duration(200)
.attr("d", function (d) {
return line5(d.datapoints);
})
.style("stroke", function (d) {
return color5(d.category);
});
}
dropdownButton.on("change", function (d) {
// recover the option that has been chosen
var selectedOption = d3.select("#selectButton").property("value")
// run the updateChart function with this selected option
updateChart(selectedOption)
})
});