Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  123] [ 3]  / answers: 1 / hits: 5712  / 10 Years ago, fri, april 25, 2014, 12:00:00

I'm using D3.js to generate a graph with response times over time. Previously I was using Google Charts but it was too heavy. D3 is nice and lightweight, but there's something I can't manage to do that I could do with Google Charts.



The problem is that those graphs sometimes span over one week, sometimes over one day, sometimes over one hour. For each case I have to manually modify how the ticks in the X axis appear. I'm doing it by comparing the first and the last values for the X axis, and checking how much time there's between them, like this:



if (dateDif < 25) { // daily
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(d3.time.format('%H:%M'))
.ticks(d3.time.hours, 3)
.orient(bottom);
}

else if (dateDif <= 170) { // ~ weekly
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(d3.time.format('%d/%m %H:%M'))
.ticks(d3.time.hours, 24)
.orient(bottom);
} else { // more than weekly
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(d3.time.format('%d/%m %H:%M'))
.ticks(d3.time.hours, 96)
.orient(bottom);
}


But that it's not good, at all, specially when there are just a few values in the chart (they're generated every minute), then no ticks appear (because it falls in the first case, and there are no enough values to span 3 hours).



Do you know of any plugin or method that automagically adapts the X axis for this kind of situations?


More From » graph

 Answers
6

d3.svg.axis() is fairly good at handling this type of behavior by default - try removing .tickFormat(...) from your axis, and setting .ticks(n) where n is the desired number of ticks you want on the axis at any scale zoom level - this might be sufficient for what you desire.



Here are a couple of related examples:



http://bl.ocks.org/mbostock/2983699



http://bl.ocks.org/mbostock/1166403


[#45750] Thursday, April 24, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
longd

Total Points: 616
Total Questions: 110
Total Answers: 101

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;