我正在try 使用d3js和reaction js创建一个Voronoi图.我在实现所需代码后遇到的问题是,Voronoi图的宽度超过了我为SVG指定的宽度.
以下是我实现的代码:
import React, { useState, useEffect, useRef, useCallback } from "react";
import * as d3 from "d3";
import "../App.css";
const mySVGRef = useRef(null);
const width = 600;
const height = 500;
// Create a Voronoi generator
const voronoi = d3.Delaunay.from(data).voronoi();
const svg = d3.select(mySVGRef.current);
svg.attr("width", width).attr("height", height);
const xScale = d3
.scaleLinear() // scale is used for linear
.domain([0, d3.max(data, (d) => d[0])])
.range([0, width]);
// Draw the Voronoi cells
svg
.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d", (d, i) => voronoi.renderCell(i))
.attr("fill", "none")
.attr("stroke", "black");
// Draw the data points
svg
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", (d) => xScale(d[0]))
//same must be done for the y scale
.attr("cy", (d) => d[1])
.attr("r", 3)
.attr("fill", "red");
//draw the x and y axis
var x_axis = d3
.axisBottom()
.scale(xScale);
svg
.append("g") //
.attr("transform", "translate(0, " + height + ")")
.call(x_axis);