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

D3.js垂直下钻柱状图调用d3.axisBottom后x轴及标签仍显示在顶部问题求助

问题原因

d3的axisBottom方法默认是将轴渲染在传入容器的y=0坐标位置,你当前的svg绘图容器已经通过transform偏移到了margin.top的位置,y=0正好对应绘图区域的顶部,所以轴会显示在顶部,没有下沉到绘图区底部。

修复步骤
  • 1、修改x轴容器初始化代码,给x轴的g容器添加向下的偏移,偏移距离等于绘图区高度height,同时删除多余的append line逻辑:
    原代码:
svg.append("g")
  .attr("class", "x axis")
  .append("line")
  .attr("x1", "100%")
  .call(d3.axisBottom(x));

替换为:

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", `translate(0, ${height})`) // 关键:将x轴向下偏移到绘图区底部
  .call(d3.axisBottom(x));
  • 2、每次下钻/返回时更新x轴的domain,保证刻度和当前显示的分类对应,需要在down和up函数里更新y域的同时添加x域更新逻辑:
    在down函数的y.domain([0, d3.max(d.children, d => d['value'])]).nice();后新增:
x.domain(d.children.map(item => item.data.name));

在up函数的y.domain([0, d3.max(d.parent.children, d => d['value'])]).nice();后新增:

x.domain(d.parent.children.map(item => item.data.name));
  • 3、(可选优化)你现在的bar元素x坐标用了barWidth * i * 1.2 +5手动计算,和x.scaleBand的定位逻辑不一致,建议删除bar的transform里的手动偏移,直接用x轴比例尺计算x坐标,保持轴刻度和柱子位置对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:39:03