You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

D3.js从数组生成多行列色表 修复代码色表完全不更新的问题

D3.js 多行色表渲染异常修复

问题原因

  • 全局变量污染:你定义的unit、colorScale是全局变量,D3执行时会先遍历所有svg元素的data回调完成数据绑定,全局变量会被最后一行配色的参数覆盖,导致所有行的色卡都用最后一组参数渲染
  • 矩形尺寸溢出:每个svg容器的高度为总高度/配色方案数量,但你给rect设置的高度是总高度500,超出了svg的可视范围,看起来就像没有渲染

修复后完整代码

HTML 部分

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>

JS 部分

color_table()
function color_table() {
  const categorical = [
    { "name" : "schemeAccent", "n": 8},
    { "name" : "schemeDark2", "n": 8},
    { "name" : "schemePastel2", "n": 8},
    { "name" : "schemeSet2", "n": 8},
    { "name" : "schemeSet1", "n": 9},
    { "name" : "schemePastel1", "n": 9},
    { "name" : "schemeCategory10", "n" : 10},
    { "name" : "schemeSet3", "n" : 12 },
    { "name" : "schemePaired", "n": 12},
  ]

  const width = 400,
        totalHeight = 500,
        rowHeight = totalHeight / categorical.length;

  const svg = d3.select('body').selectAll('color-row')
    .data(categorical)
    .enter()
    .append('svg')
    .attr('width', width)
    .attr('height', rowHeight)
    .style('border','1px solid red')
  
  svg.selectAll(".bars")
    .data(d => {
      const n = d.n
      const unit = width / n
      const colorScale = d3.scaleOrdinal(d3[d.name])
      // 把当前行的配置绑定到每个色块数据上,避免全局变量覆盖
      return d3.range(n).map(idx => ({idx, unit, colorScale}))
    })
    .enter().append("rect")
      .attr("class", "bars")
      .attr("x", d => d.idx * d.unit)
      .attr("y", 0)
      .attr("height", rowHeight)
      .attr("width", d => d.unit)
      .style("fill", d => d.colorScale(d.idx))
}

内容的提问来源于stack exchange,提问作者lucky1928

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 09:24:05