D3.js图表刻度标记与标签不显示问题求助
问题:X轴月度刻度标记未显示(TypeScript React + Vite + D3.js)
我使用TypeScript React搭配Vite作为构建工具,想要生成一个X轴按指定范围每月显示刻度标记的图表,但目前图表在HTML中显示时,刻度标记并未出现。
编写的代码如下,当前仅能显示空的X轴和Y轴:
export const App = () => { const data = useMemo(() => { // X轴范围数据 return [ new Date("2022-01-01"), new Date("2022-02-01"), new Date("2022-03-01"), new Date("2022-04-01"), new Date("2022-05-01") ] }, []) const svgRef = useRef<SVGSVGElement>(null); const width = 500 const height = 500 useEffect(() => { if (svgRef.current) { const svg = d3.select(svgRef.current); // 移除所有SVG元素 svg.selectAll("*").remove(); // 生成X、Y轴的范围和定义域 // X轴宽度500px,定义域为日期的最小到最大值 const xScale = d3.scaleTime().range([0, width]).domain(d3.extent(data) as [Date, Date]); // Y轴为线性刻度,范围从height到0 const yScale = d3.scaleLinear().range([height, 0]) // 创建X轴 svg.append("g") .attr("transform", `translate(0,${height})`) // 将X轴移至图表底部 .call( d3.axisBottom(xScale) // 生成带刻度标记的轴 .ticks(d3.timeMonth.every(1)) // 刻度间隔为1个月 .tickFormat((d, i) => { // 刻度文本显示月份名称 if (d instanceof Date) { return d3.timeFormat("%B")(d) as string } else { return "" + d } })) // 生成Y轴(无刻度) svg.append("g").call(d3.axisLeft(yScale)) } }, [data]) return ( <> <svg ref={svgRef} width={width} height={height} /> </> ) }
当前效果:仅显示空的X轴和Y轴,如图所示:
内容的提问来源于stack exchange,提问作者M. Nicol
相关产品推荐
相关产品推荐

