【问题标题】:Updating Barchart d3.js and React更新 Barchart d3.js 和 React
【发布时间】:2022-09-24 12:09:10
【问题描述】:

我正在尝试使用 React 和 D3 更新条形图。我试图实现的功能基本上就是这个 d3 示例中显示的功能:https://d3-graph-gallery.com/graph/barplot_button_data_hard.html。因此,我试图使代码适应我的反应应用程序。

因此,当我的状态随状态中的数据发生变化时,我想更新数据。我面临的问题是 y 轴根本没有显示任何刻度,并且 x 轴没有正确更新刻度,而是将新的刻度值添加到轴上。

我的代码如下:

const BarChart = () => {
  let statePlots = useSelector((state) => state.plots);
  const data = useSelector((state) => state.plots.data);
  const ref = useRef();

  useEffect(() => {
    const svg = d3.select(ref.current);
    // set the dimensions and margins of the graph
    const margin = { top: 30, right: 30, bottom: 70, left: 60 },
      width = 460 - margin.left - margin.right,
      height = 400 - margin.top - margin.bottom;

    // add to the svg object of the page
    svg
      .attr(\"width\", width + margin.left + margin.right)
      .attr(\"height\", height + margin.top + margin.bottom)
      .append(\"g\")
      .attr(\"transform\", `translate(${margin.left},${margin.top})`);

    // Initialize the X axis
    const x = d3.scaleBand().range([0, width]).padding(0.2);
    const xAxis = svg.append(\"g\").attr(\"transform\", `translate(0,${height})`);

    // Initialize the Y axis
    const y = d3.scaleLinear().range([height, 0]);
    const yAxis = svg.append(\"g\").attr(\"class\", \"myYaxis\");

    // Update the X axis
    x.domain(data.map((d) => d.group));
    xAxis.call(d3.axisBottom(x));

    // Update the Y axis
    y.domain([0, d3.max(data, (d) => d.value)]);
    yAxis.transition().duration(1000).call(d3.axisLeft(y));

    // Create the u variable
    var u = svg.selectAll(\"rect\").data(data);

    u.join(\"rect\") // Add a new rect for each new elements
      .transition()
      .duration(1000)
      .attr(\"x\", (d) => x(d.group))
      .attr(\"y\", (d) => y(d.value))
      .attr(\"width\", x.bandwidth())
      .attr(\"height\", (d) => height - y(d.value))
      .attr(\"fill\", \"#69b3a2\");
  }, [statePlots]);

  return (
    <div>
      <div>D3 Plot</div>
      <svg ref={ref}></svg>
    </div>
  );
};

上面的代码确实切换了数据,但正如我所提到的,它没有正确更新刻度。我对 d3.js 很陌生,也不是 React 专家。任何帮助表示赞赏。提前致谢

标签: javascript reactjs d3.js bar-chart


【解决方案1】:

我认为你没有调用 enter 方法,而不是 join 你应该调用 append

所以你能试试这个,请检查一下

       u
        .enter()
        .append("rect")
        .transition()
        .duration(1000)
        .attr("x", d => x(d.group))
        .attr("y", d => y(d.value))
        .attr("width", x.bandwidth())
        .attr("height", d => height - y(d.value))
        .attr("fill", "#69b3a2")

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 2015-10-18
    • 2014-07-14
    • 2012-03-27
    • 1970-01-01
    • 2013-01-25
    • 2015-02-20
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多