Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

d3.js - How can I define a maximal amount of ticks in a d3.svg.axis

I have the problem that the labels of my d3.svg.axis are sometimes overlapping. Therefor I would like to reduce the maximal amount of ticks and labels to a certain amount.

I can not seem to find a solution in the API documentation.

I can not use axis.tickValues() because the range is dynamic and can go from several hours to several years.

I have tried using axis.ticks(9) but it does not seem to have an effect. You can look at an example on bl.ocks.org/3181719.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One of these two should do it for you. Just specify axis.ticks(10) to specify the number of tick marks or axis.tickValues([1,2,4]) to specify the actual tick marks that should appear.

Since you are using dates, you'll need to do something like this:

 .ticks(d3.time.weeks, 2)

You can read more about time intervals at https://github.com/mbostock/d3/wiki/Time-Intervals. You can see an example about how I do this at http://bl.ocks.org/1962173 to update the ticks based on the length of time being shown.

if ((maxExtent - minExtent) > 1468800000) {
    x1DateAxis.ticks(d3.time.mondays, 1).tickFormat(d3.time.format('%a %d'))
    x1MonthAxis.ticks(d3.time.mondays, 1).tickFormat(d3.time.format('%b - Week %W'))        
}
else if ((maxExtent - minExtent) > 172800000) {
    x1DateAxis.ticks(d3.time.days, 1).tickFormat(d3.time.format('%a %d'))
    x1MonthAxis.ticks(d3.time.mondays, 1).tickFormat(d3.time.format('%b - Week %W'))
}
else {
    x1DateAxis.ticks(d3.time.hours, 4).tickFormat(d3.time.format('%I %p'))
    x1MonthAxis.ticks(d3.time.days, 1).tickFormat(d3.time.format('%b %e'))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...