Default D3 Chart

By default, d3.ScaleLinear tries to create 10 ticks using the d3.ticks(start, stop, count) function.

Want to know how the nice function works? . See: Nice function demo

The d3.ticks(start, stop, count) function.

Returns an array of approximately count + 1 uniformly-spaced, nicely-rounded values between start and stop (inclusive). Each value is a power of ten multiplied by 1, 2 or 5.

The ticks are generated using the following algorithm:

  1. The raw step size is calculated like:
    step=stopstartmax(0,count)\text{step} = \frac{\text{stop} - \text{start}}{\max(0, \text{count})}
  2. 4.3=452max(0,10)\text{4.3} = \frac{\text{45} - \text{2}}{\max(0, \text{10})}
  3. Find the magnitude of the step size by taking the base-10 logarithm of the step and flooring it :
    magnitude=log10(step)\text{magnitude} = \lfloor\log_{10}\left(\text{step}\right)\rfloor
    The parentheses around log10(step) mean a floor function
    Step 1: =log10(step)=0.6334684555795865\text{Step 1: } = \log_{10}(\text{step}) = 0.6334684555795865

    Step 2: log10(step)=0\text{Step 2: } \left\lfloor \log_{10}(\text{step}) \right\rfloor = 0
  4. Adjust the step size to be a multiple of 1, 2, or 5 of the order of magnitude:
    error=step10magnitude\text{error} = \frac{\text{step}}{10^\text{magnitude}}
    =4.3100=4.3 = \frac{\text{4.3}}{10^\text{0}} = 4.3


    Determine the factor
    if (error50)factor=10\text{if } (\text{error} \geq \sqrt{50}) factor = 10
    50)=7.0710678118654755\sqrt{50}) = 7.0710678118654755

    if (error10)factor=5\text{if } (\text{error} \geq \sqrt{10}) factor = 5
    10)=3.1622776601683795\sqrt{10}) = 3.1622776601683795

    if (error2)factor=2\text{if } (\text{error} \geq \sqrt{2}) factor = 2
    2)=1.4142135623730951\sqrt{2}) = 1.4142135623730951

    else factor=1\text{else } factor = 1

    Error = 4.3 -> factor = 5
  5. inc=10power×factor\text{inc} = 10^{\text{power}} \times \text{factor}
    =
    100×5=510^{\text{0}} \times \text{5} = 5

    i1=round(startinc)i_1 = \text{round}\left( \frac{\text{start}}{\text{inc}} \right)
    =
    round(25)\text{round}\left( \frac{\text{2}}{\text{5}} \right)
    = 0

    i2=round(stopinc)i_2 = \text{round}\left( \frac{\text{stop}}{\text{inc}} \right)
    =
    round(455)\text{round}\left( \frac{\text{45}}{\text{5}} \right)
    = 9
    i1 and i2 are the indices that represent the first (i1) and the last (i2) tick values in the range between start and stop.
  6. Resulting ticks = 5,10,15,20,25,30,35,40,45
  7. The full code also handles the cases where start is greater then stop. And when power is negative. See: github.com/d3/d3-array/blob/src/ticks.js