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
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.
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;
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
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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With