D3.js - 分组条形图 - 更新输入数据时出错

问题描述 投票:0回答:1

我正在尝试使用分组条形图来显示测试问题的回答表现。我创建了两个 .svg 文件,其结果我的可视化应该能够在它们之间切换。我可以毫无问题地加载和可视化第一组数据,但是当我选择第二组时,会在未删除的旧条形之上创建新条形。

这是我到目前为止所得到的:

<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() 等,但没有运气!任何建议将不胜感激!

html d3.js visualization grouped-bar-chart
1个回答
0
投票

通常,如果您有一个经常被调用的函数,看到

append
应该会引发危险信号(除非
append
仅出现在
enter
选择上)。

在您的代码中,每次运行

update
时,svg 都会为 x 轴附加一个新的组元素。相反,它应该选择旧的 x 轴并更新它。

  svg.selectAll("g.my-x-axis").data([null]).join('g')
    .attr("class", "my-x-axis")
    .attr("transform", `translate(0, ${height})`)
    .call(d3.axisBottom(x).tickSize(0));

这将选择旧的 x 轴组(如果存在),或者如果不存在则创建一个。我们的空数据数组

[null]
仅包含一个空元素,因此只会创建一个 x 轴。

对于添加矩形的代码也可以这样说。您确实使用输入/更新/输入模式连接数据,但只调用了输入。这是因为在进入/更新/退出之前,您使用

svg.append("g").selectAll("g")
将一个空组添加到您的 svg 中。因为您总是附加一个空组,所以它永远不会有任何内容可以更新。因此,它正在创建新的组,输入数据,并且这些组相互堆叠。相反,您应该创建一个组一次,然后在下次选择它(就像我上面显示的 x 轴一样)。

© www.soinside.com 2019 - 2024. All rights reserved.