You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 00:10:18