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

React项目中D3.js弦图仅显示右下四分之一问题求助

问题描述

React项目中使用D3.js开发弦图时,图表仅能呈现右下侧四分之一区域。

问题原因分析
  • SVG元素错误使用transform属性:SVG元素本身不支持transform属性,直接给SVG设置translate不会生效,导致图表无法居中。
  • 图表尺寸与半径不匹配:设置的圆弧半径(innerRadius=200、outerRadius=210)超过了计算后的SVG宽高(width=330、height=360),超出部分无法显示。
  • 缺少居中容器组:弦图需要以SVG中心为原点绘制,未创建居中的g容器组,所有元素默认从SVG左上角开始绘制,导致仅右下部分可见。
修复后的代码
const ChordDiagram = ({ data }) => {
  const mySVGRef = useRef(null);
  const wrapperRef = useRef();

  // 设置图表的边距和尺寸
  const margin = { top: 10, right: 30, bottom: 30, left: 40 };
  const width = 400 - margin.left - margin.right;
  const height = 400 - margin.top - margin.bottom;
  // 根据SVG尺寸计算合适的半径
  const innerRadius = Math.min(width, height) / 2 - 30;
  const outerRadius = innerRadius + 20;

  useEffect(() => {
    const svg = d3.select(mySVGRef.current);

    // 清空SVG内容避免重复渲染
    svg.html(null);

    // 设置SVG的实际宽高
    svg
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom);

    // 创建主容器组,平移到SVG中心
    const mainGroup = svg.append("g")
      .attr("transform", `translate(${margin.left + width/2}, ${margin.top + height/2})`);

    // 计算弦图所需数据
    const res = d3
      .chord()
      .padAngle(0.05)
      .sortSubgroups(d3.descending)(data);

    // 绘制分组圆弧
    mainGroup
      .datum(res)
      .append("g")
      .selectAll("g")
      .data(d => d.groups)
      .join("g")
      .append("path")
      .style("fill", "grey")
      .style("stroke", "black")
      .attr("d", d3.arc().innerRadius(innerRadius).outerRadius(outerRadius));

    // 绘制分组间的连接线
    mainGroup
      .datum(res)
      .append("g")
      .selectAll("path")
      .data(d => d)
      .join("path")
      .attr("d", d3.ribbon().radius(innerRadius))
      .style("fill", "#69b3a2")
      .style("stroke", "black");
  }, [data]);

  return (
    <div className="row">
      <div className="col-lg-1"></div>
      <div className="col-lg-10 chart-div" ref={wrapperRef}>
        <svg ref={mySVGRef}></svg>
      </div>
      <div className="col-lg-1"></div>
    </div>
  );
};

export default ChordDiagram;
关键修复点说明
  • 移除SVG的transform属性:改为创建内部g容器组,通过translate将其定位到SVG中心,确保弦图以中心为原点绘制。
  • 动态计算半径:根据SVG的最小边尺寸计算圆弧半径,避免半径超出SVG范围。
  • 修正SVG尺寸设置:将SVG的宽高设置为width+margin.left+margin.right和height+margin.top+margin.bottom,确保边距空间被包含在内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:00:46