【问题标题】:D3 Chart does not redraw on new dataD3 图表不会在新数据上重绘
【发布时间】:2019-06-21 20:15:06
【问题描述】:

使用 react 我绘制了一个 D3 散点图。当我尝试通过我在开始时初始化的svg 在图表上添加新线时,它可以工作,即使用 svg 中呈现的按钮和 onlick 函数时。

当我尝试使用父母的道具执行此操作时,添加线条的功能会被触发,但不会添加线条。我已经阅读了有关使用enter() 的其他帖子,但这不起作用。我认为错误的是我设置 div 结构以安装原始 SVG 的方式,因为我有一个类为 chart-container 的 div 和一个 id 为 chart 的 div,我在其中添加了 SVG。有没有人认为我在添加行时选择svg 的方式是错误的?我不明白为什么线条没有呈现在 D3 图表上。

import React, { useEffect, useLayoutEffect } from 'react';
import * as d3 from 'd3';

import './Chart.css';

const Chart = (props) => {
  useEffect(() => {
    drawChart(props.data)
  }, [props.columnType]);

  useLayoutEffect(() => {
    if (showLines) {
      addLines(props.data)
      return
    } else {
      removeLines()
    }
  }, [props.showLines]);

  const addLines = (data) => {
      const x = d3.scaleLinear().range([0, width]);
      const y = d3.scaleLinear().range([height, 0]);
      const parsedData = parseData(data, columnType);

      parsedData.forEach((dataSet, index) => {
        const { points } = dataSet;
        const line = d3.line()
          .x((d) => x(d.x))
          .y((d) => y(d.yhat));
        // If I use this selection, I cannot add the lines
        d3.select("svg").enter().append("path")
          .datum(points)
          .attr("class", `line`)
          .attr("d", line);
      });
  }

  const drawChart = (data) => {
    ..... // Other code not added (related to configuring the graph)
    // If I use this SVG I can add the lines
    const svg = d3.select("#chart").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .attr("id", "chart-svg")
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    ..... // other code not added (related to rendering the points using the data)

  }

  return (
    <div className="chart-container">
      <div id="chart"></div>
    </div>
  );
}

【问题讨论】:

标签: reactjs d3.js svg redraw


【解决方案1】:

想通了。我需要再次重置 x 和 y 范围,因为它正在将线条渲染到屏幕外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    相关资源
    最近更新 更多