我试着用一个分组条形图来显示对测试问题的回答的表现.我已经创建了两个. svg文件,其中的结果我的可视化应该能够在它们之间切换.我可以毫无问题地加载和可视化第一组数据,但当我 Select 第二组时,新的条条会在旧条上创建,而这些条不会被删除.
以下是我目前掌握的情况:
<script>
// There's a lot of this script here: https://d3-graph-gallery.com/graph/barplot_grouped_basicWide.html
// set the dimensions and margins of the graph
const margin = {top: 10, right: 30, bottom: 20, left: 50},
width = 460 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// append the svg object to the body of the page
let svg = d3.select("#my_dataviz")
.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})`);
function update (test_no){
// Reading Data from CSV
d3.csv(`bardisect_${test_no}.csv`).then( function(data) {
// Creates the subgroups using group names
let subgroups = data.columns.slice(1)
// Making a map of the subgroups for the x axis
let groups = data.map(d => d.groups)
// Add X axis
let x = d3.scaleBand()
.domain(groups)
.range([0, width])
.padding([0.2])
svg.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(x).tickSize(0));
// Add Y axis
let y = d3.scaleLinear()
.domain([0, 100])
.range([ height, 0 ]);
svg.append("g")
.call(d3.axisLeft(y));
// creating separate x axis for subgroups
let xSubgroup = d3.scaleBand()
.domain(subgroups)
.range([0, x.bandwidth()])
.padding([0.05])
// colours for the subgroups
let color = d3.scaleOrdinal()
.domain(subgroups)
.range(['green','red','grey'])
// Show the bars
svg.append("g")
.selectAll("g")
// Looping through each group to shoow the right numbers
.data(data)
.join(
enter => {
enter
let sel = enter
.append("g")
.attr("transform", d => `translate(${x(d.groups)}, 0)`)
return sel;
})
.selectAll("rect")
.data((d) => { return subgroups.map(function(key) { return {key: key, value: d[key]}; }); })
.join(
(enter) => {
enter
.append("rect")
.attr('fill', 'white')
.attr("x", d => xSubgroup(d.key))
.attr("y", d => y(d.value))
.attr("width", xSubgroup.bandwidth())
.attr('height', 0)
.transition()
.duration(1000)
.attr("height", d => height - y(d.value))
.attr("fill", d => color(d.key))
},
(update) => {
update
.transition()
.duration(1000)
.attr("fill", d => color(d.key))
.attr("x", d => xSubgroup(d.key))
.attr("width", xSubgroup.bandwidth())
.attr("height", d => height - y(d.value))
.attr("y", d => y(d.value))
},
(exit) => {
exit
.transition()
.duration(1000)
.attr('height', 0)
.remove();
}
)
});
}
//updating the test selection
let select = d3.select('#test_no');
select.on('change', function() {
console.log(this.value);
update(this.value);
})
update('02');
</script>
我对D3很陌生,一直在玩更新,退出和. remove()等,但没有运气!任何建议将不胜感激!