[英]Chart in d3js not showing up in react app
我正在尝试按照此处的教程进行操作,但使用的是 React 应用程序。 图表没有显示,我不确定我做错了什么,请帮忙。 我正在使用 d3 v7 并响应 17。我没有收到任何错误,但按钮显示,因此组件被正确调用。
这是我的组件:
import * as d3 from 'd3'
import * as React from 'react'
import { useState, useEffect} from 'react'
const PieChart = (props) => {
const ref = React.createRef()
useEffect(() => {
draw()
});
// set the dimensions and margins of the graph
const width = 450, height = 450, margin = 40;
// The radius of the pieplot is half the width or half the height (smallest one). I subtract a bit of margin.
const radius = Math.min(width, height) / 2 - margin;
// set the color scale
const color = d3.scaleOrdinal()
.domain(["a", "b", "c", "d", "e", "f"])
.range(d3.schemeDark2);
// create 2 data_set
const data1 = {a: 9, b: 20, c:30, d:8, e:12}
const data2 = {a: 6, b: 16, c:20, d:14, e:19, f:12}
const svg = d3.select(".PieChart")
// A function that create / update the plot for a given variable:
const update = (data) => {
if (data == "data1"){
data = data1;
}else{
data = data2;
}
// Compute the position of each group on the pie:
const pie = d3.pie()
.value(function(d) {return d[1]; })
.sort(function(a, b) { return d3.ascending(a.key, b.key);} ) // This make sure that group order remains the same in the pie chart
const data_ready = pie(Object.entries(data))
// map to data
const u = svg.selectAll("path")
.data(data_ready)
// Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
u
.join('path')
.transition()
.duration(1000)
.attr('d', d3.arc()
.innerRadius(0)
.outerRadius(radius)
)
.attr('fill', function(d){ return(color(d.data[0])) })
.attr("stroke", "white")
.style("stroke-width", "2px")
.style("opacity", 1)
}
const draw = () => {
svg.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", `translate(${width/2}, ${height/2})`);
// Initialize the plot with the first dataset
update("data1")
};
return <div ref={ref} >
<button onClick={update("data1")}>Data 1</button>
<button onClick={update("data2")}>Data 2</button>
<div className="PieChart" />
</div>
}
export default PieChart
这是我得到的,没有图表
我认为有很多事情需要解决。 首先是ref
的用法。 你必须做const ref = React.useRef()
即使用useRef
而不是createRef
。 此外, ref 必须设置为svg
元素而不是div
。
“几乎”工作代码在这里。 https://codesandbox.io/s/flamboyant-heisenberg-vppny?file=/src/pie.js
我说几乎是因为图表不会在页面加载时呈现! 我不知道为什么(我对反应不是很熟悉)。 要渲染图表,请将width
或height
的值从 450 更改为 451。我不知道为什么会这样,但确实如此。
一个页面加载了图表,按钮和图表转换工作正常。
如果您想知道如何在页面加载时呈现图表,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.