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

如何让D3折线图Y轴刻度按10递增而非5?

调整D3折线图Y轴刻度步长为10

要将Y轴刻度步长从5改为10,你可以手动指定刻度值数组,让D3按照需求的间隔生成刻度,以下是两种简单的实现方式:

方法一:直接在轴配置中传入刻度数组

利用d3.range()生成从50到120、步长为10的刻度值数组,传给轴的ticks()方法:

diaGraph
   .append('g')
   .attr('class', 'y-axis')
   .call(d3.axisLeft(dia_yScale).ticks(d3.range(50, 121, 10)))

方法二:先定义刻度数组再传入

如果需要复用刻度数组,可以先单独生成,再通过tickValues()传入:

// 生成50、60、70...120的刻度数组
const yTickValues = d3.range(50, 121, 10);

diaGraph
   .append('g')
   .attr('class', 'y-axis')
   .call(d3.axisLeft(dia_yScale).tickValues(yTickValues))

修改后的完整相关代码

const { data } = props

const width = 800
const diaHeight = 200

const diaGraph = d3
   .select('#dia-graph')
   .append('svg')
   .attr('width', width + margin.left + margin.right)
   .attr('height', diaHeight + margin.top + margin.bottom)
   .append('g')
   .attr('transform', `translate(${margin.left},${margin.top})`)
   .data(data)

const dia_yScale = d3
   .scaleLinear()
   .range([diaHeight, 0])
   .domain([50, 120])

// 使用方法一的写法配置Y轴
diaGraph
   .append('g')
   .attr('class', 'y-axis')
   .call(d3.axisLeft(dia_yScale).ticks(d3.range(50, 121, 10)))

D3默认会根据图表尺寸和定义域自动计算刻度步长,所以之前生成了步长为5的刻度。通过手动指定刻度值,就能强制让Y轴按照10的步长显示刻度,解决拥挤问题。

内容的提问来源于stack exchange,提问作者DylanD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:18:26