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

D3.js中能否将.tickValues置于条件语句中按需执行?

Conditionally Applying tickValues in D3.js X-Axis

Absolutely! You can conditionally apply the .tickValues() method to your D3 axis—you just need to structure your code differently than trying to embed it inside the tickFormat callback. Here's how to do it:

Step-by-Step Solution

First, initialize your axis with the tickFormat logic as you already have:

var xAxis = d3.axisBottom(x) 
  .tickFormat(function (d, i) { 
    if (interval_size === "15" || interval_size === "30") { 
      return testStringArray[i]; 
    } else { 
      return dateArray[i]; 
    } 
  });

Next, apply .tickValues() only when your specific condition is met. Since D3 axis methods return the axis object itself, you can reassign the xAxis variable after adding the conditional configuration:

// Replace this condition with your exact requirement
if (interval_size !== "15" && interval_size !== "30") {
  xAxis = xAxis.tickValues(x.domain().filter(function (d, i) { 
    return !(i % 2); 
  }));
}

Why Your Previous Attempt Didn't Work

The tickFormat function is designed solely to format the text of individual tick labels—it can't control which ticks are displayed. The .tickValues() method is a top-level configuration for the axis, so it needs to be called directly on the axis object, not nested inside the tickFormat callback.

This approach keeps your code clean and ensures that the tick filtering logic only runs when your condition is satisfied.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:18:24