我试着用一个分组条形图来显示对测试问题的回答的表现.我已经创建了两个. 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()等,但没有运气!任何建议将不胜感激!

推荐答案

通常,如果您有一个经常被调用的函数,看到append应该会发出危险信号(除非append只在enter选项上).

在代码中,每次运行update时,svg都会为x轴追加一个新的group元素.相反,它应该 Select 旧的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));

这将 Select 旧的x轴组(如果存在),或创建一个如果不存在.我们的空数据数组[null]只包含一个空元素,所以只创建一个x轴.

同样的道理也适用于添加矩形的代码.您确实使用ENTER/UPDATE/ENTER模式连接数据,但只调用了ENTER.这是因为在Enter/UPDATE/Exit之前,您向您的SVG添加了一个空组,其值为svg.append("g").selectAll("g").因为您总是附加一个空组,所以它永远不会有任何需要更新的内容.因此,它正在创建新的组,输入数据,这些组堆叠在一起.相反,您应该创建一次组,并在下一次 Select 它(就像我上面为x轴显示的那样).

Html相关问答推荐

使用网格时图像溢出容器高度

R-markdown中的非顺序列表

为什么在添加文本时网格区域会调整大小?

我无法使用背景图像css,因为我在VS代码中将照片放在不同的文件夹中

如何在排序上重用参数?

每个元素的CSS网格高度相等,以保持响应性

水平卷轴的内容保持堆叠

SCSS动画错误:心脏在页面刷新时启动动画,原因是:Checked和:Not(:Checked) Select 器

渐变进度条位置

如何使不断增长的div不溢出其包含固定div的父级

配置了 HTML 视口的 Google Apps 脚本移动网络应用程序无法正确显示

perl hdb 调试器:浏览器以错误的编码显示 UTF-8 源代码

如何修剪 flex: 1 内的垂直文本?

为什么即使我点击其他地方,我的 contenteditable="true" 也会被激活?

pull-right 不适用于 bootstrap alert 内的按钮

如何截断一些文本并用双引号引起来?

在包含 html 标签的字符串的子字符串中应用不同的样式

当另一个 div 的高度改变或执行其内容的换行时,将 flex 方向更改为列

标题之间和之后的 Hr 线

将固定/绝对伪元素放置在相对 div(具有滚动条)内,始终位于底部