我正在try 使用d3js在一个reaction js项目中创建一个和弦图.我遇到的问题是,我的图表显示部分正常,因为它只显示图表的右下角(只有四分之一).下面是一个图表示例:https://codesandbox.io/s/amazing-leaf-3lgjwc,下面是我的图表组件的代码:

const ChordDiagram = ({ data }) => {
  const mySVGRef = useRef(null);
  const wrapperRef = useRef();

  // set the dimensions and margins of the graph
  var margin = { top: 10, right: 30, bottom: 30, left: 40 },
    width = 400 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

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

    //so that we dont have duplication
    svg.html(null);
    svg
      .attr("width", width)
      .attr("height", height + margin.top + margin.bottom)
      .attr("transform", `translate(${margin.top * 12},${margin.top * 12})`);

    // give this matrix to d3.chord(): it will calculates all the info we need to draw arc and ribbon

    const res = d3
      .chord()
      .padAngle(0.05) // padding between entities (black arc)
      .sortSubgroups(d3.descending)(data);

    // add the groups on the inner part of the circle
    svg
      .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(200).outerRadius(210));

    // Add the links between groups
    svg
      .datum(res)
      .append("g")
      .selectAll("path")
      .data((d) => d)
      .join("path")
      .attr("d", d3.ribbon().radius(200))
      .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;

推荐答案

以下是您应该解决的问题:

  1. 不需要将变换设置为<svg>.删除:
svg.attr("transform", `translate(${margin.top * 12},${margin.top * 12})`);
  1. 不需要设置svg个基准(在两种情况下).

  2. svg下创建一个<g>元素,并将其原点设置为SVG的中心:

const container = svg.append('g')
  .attr('transform', `translate(${margin.left + width/2},${margin.top + height/2})`);

,然后将所有元素(组和链接)附加到container以下

Reactjs相关问答推荐

使用useEffect挂钩获取数据

过滤对象数组并通过迭代对象数组将属性放入新数组

如何将Redux工具包添加到expo (SDK 50)项目?

如何创建react router v6的自定义子路由?

如何用Reaction做交互式的MathML?

有没有办法在Shopify中显示自定义计算的交货日期?

我如何在不被 destruct 的情况下将导航栏固定在顶部?

React路由dom布局隐藏内容

有没有比;KeyableShell;组成部分

错误:操作必须是普通对象.使用自定义中间件进行异步操作. Redux/工具包

如何在react 中过滤数组的数组?

无法读取未定义的属性(阅读 'editQuoteModalShown')reactredux

try 从 React JS 构建此教程游戏但无法继续前进

使用dayjs时如何在输入类型日期时间本地字段中设置默认值?

单击按钮或文本从一个组件移动到另一个组件

使用 React.UseEffect 从 api 获取但我的清理返回不起作用

将 Material UI 菜单渲染为

将 dict 值转换并插入到react 钩子的列表中

为什么 React 会多次调用我的应用程序的某些函数?

您无权使用阻止 webRequest 侦听器.请务必在 list 中声明 webRequestBlocking 权限