d3 / d3-axis

Human-readable reference marks for scales.

Home Page:https://d3js.org/d3-axis

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Updating tickValues after axis scaling

ux-engineer opened this issue · comments

I've done an Y axis scaling slider. It worked fine with ticks(50) and my custom implementation minor tick hiding... But even though Y axis range had equal amounts of positive and negative, sometimes zero was not drawn as a major tick.

After doing custom calculation of tick values, I noticed that when 'tickValues' is called again it does not replace the previous ticks but rather draws an another set of ticks.

How about an improvement that when tickValues() is called with new data, it would replace the previously drawn ticks?

If I'd just remove those ticks like so:

d3.selectAll('.focus .axis--y1 .tick').remove();
yAxis.tickValues(yTickValues);
d3.selectAll('.focus .axis--y1 .tick')
    .filter(function (d, i) { return !isMajorTick(i); })
    .classed("minor", true);

It doesn't work as the removal operation takes time...and implementing an event listener callback for chaining this these further operations would seem a too cumbersome solution.

Calling axis.tickValues does set the axis’ tick values, but this does not have an effect until you re-render the axis (or render a new axis). This behavior is true of any axis property. An axis doesn’t maintain a relationship with it’s rendered elements. Think of it more like a rubber stamp that you can apply (or re-apply) to an SVG G element.

So, if you want to set new tick values, you’d say:

yAxis.tickValues(yTickValues);
d3.select(".axis--y1").call(yAxis);

Or all in one go:

d3.select(".axis--y1").call(yAxis.tickValues(yTickValues));

This will exit old ticks and enter or update new ticks as appropriate. If you want to customize the tick appearance, you can do that after re-rendering the axis.

Please use Stack Overflow tag d3.js to ask for help. Although I make an effort to assist everyone that asks, I am not always available to provide help promptly or directly. Stack Overflow provides a better collaborative forum for self-help: tens of thousands of D3-related questions have already been asked there, and some answered questions may be relevant to you.

When asking for help, please include a link to a live example that demonstrates the issue, preferably on bl.ocks.org. It is often impossible to debug from code snippets alone. Isolate the issue and reduce your code as much as possible before asking for help. The less code you post, the easier it is for someone to debug, and the more likely you are to get a helpful response.

If you have a question about D3’s behavior and want to discuss it with other users, also consider the d3-js Google Group or joining the d3-js Slack.

Thank you! 🤗