Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3v4 time scale axis error in ticks display

I'm actually experimenting D3 v4 and i face a problem in ticks display on time axe.

Here is the difference between v3 and v4 display

The v3 code i try to transpose is the following

var x = d3.time.scale().range([0, width]);
var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(6);
x.domain(d3.extent(data.map(function(d) { return d.date; })));

gXAxis.call(xAxis);

And the v4 code i made is this

import {scaleTime, scaleLinear} from 'd3-scale';
import {axisBottom, axisLeft} from 'd3-axis';
import {select} from 'd3-selection';
import {extent} from 'd3-array';


let x = scaleTime().range([0, width])
    .domain(extent(data.map(function(d) { return d.date; })));

let xAxis = axisBottom().scale(x).ticks(6);

gXAxis.call(xAxis);

Does someone have an idea of my mistake? I guess a wrong usage of the v4 API but got difficulties finding documentation on this alpha version.

Thanks

like image 953
onicollet Avatar asked May 03 '16 08:05

onicollet


People also ask

How to get the number of ticks in D3 axis?

The d3.axis.ticks () Function in D3.js is used to control which ticks are displayed by the axis. This function returns the axis generator Parameters: This function accepts the following parameters. count/interval: This parameter is used to display the number of ticks.

Why do my axis values overlap in D3?

The format of the values (especially on the x axis) is too wide and this type of overlap was bound to happen eventually. Good news. D3 has got us covered. The axis component includes a function to specify the number of ticks on an axis. All we need to do is add in the function and the number of ticks like so;

How to control which ticks are displayed by the Axis?

The d3.axis.ticks () Function in D3.js is used to control which ticks are displayed by the axis. This function returns the axis generator

What is the time scale in D3?

D3’s time scale is implemented as an extension of d3.scale.linear () that represents a domain as JavaScript Date objects. Unlike linear scale values, time scale domain values are stored as dates rather than numbers.


1 Answers

The key is this line:

let xAxis = axisBottom().scale(x).ticks(6);

Try changing like so:

let xAxis = axisBottom(x).ticks(6);

For a full working example see - jsFiddle

EDIT

Improved the above js fiddle to include formatting.

Snippet from jsFiddle below:

let x = d3
  .scaleTime()
  .range([0, totalWidth])
  .domain(d3.extent(data));

let xAxis = d3
  .axisBottom(x)
  .ticks(d3.timeDay, 1)
  .tickFormat(d3.timeFormat("%a %d"));
like image 98
Ashley Coolman Avatar answered Oct 19 '22 19:10

Ashley Coolman