【发布时间】: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 专家。任何帮助表示赞赏。提前致谢
-
你能包括一个minimal reproducible example吗?
标签: javascript reactjs d3.js bar-chart