D3.js中能否将.tickValues置于条件语句中按需执行?
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

