Reputation: 832
Here are the dates that I am parsing:
2010-12-31
2011-12-31
2012-12-31
2013-12-31
2014-12-31
2015-12-31
2016-12-31
Here is my code:
this.x = d3.scaleTime().domain(d3.extent(this.dataArray, d => {return d[ this.xType ];})).range([ this.margin.left, this.width - this.margin.right ]);
this.y0 = d3.scaleLinear().domain([ this.getMin(this.yType1, this.yType0), this.getMax(this.yType1, this.yType0) ]).range([ this.height, 0 ]);
this.y1 = d3.scaleLinear().domain([ this.getMin(this.yType1, this.yType0), this.getMax(this.yType1, this.yType0) ]).range([ this.height, 0 ]);
this.xAxis = d3.axisBottom(this.x);
this.yAxisLeft = d3.axisLeft(this.y0).ticks(5);
this.yAxisRight = d3.axisRight(this.y1).ticks(5);
The problem is that the first date (2010) is being truncated from the x-axis and an additional tick is being added in the very end, however the chart is drawn right.
If I add .nice(this.dataArray.length)
to this.x = ...
, the year 2010 is added with 2017 at the very end.
How can I fix this problem? Thank you.
Upvotes: 0
Views: 52
Reputation: 102174
You can map
your data:
var ticks = data.map((d)=>d);
And use this array in your tickValues
:
var axis = d3.axisBottom(scale)
.tickValues(ticks);
Here is a demo:
var width = 500,
height = 100;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var parse = d3.timeParse("%Y-%m-%d");
var data = ["2010-12-31",
"2011-12-31",
"2012-12-31",
"2013-12-31",
"2014-12-31",
"2015-12-31",
"2016-12-31"
];
data.forEach((d, i, a) => a[i] = parse(d));
var ticks = data.map((d) => d)
var format = d3.timeFormat("%Y")
var scale = d3.scaleTime()
.domain(d3.extent(data, d => d)).range([20, width - 20]);
var axis = d3.axisBottom(scale).tickValues(ticks).tickFormat((d) => format(d));
var gX = svg.append("g")
.attr("transform", "translate(0,50)")
.call(axis);
<script src="https://d3js.org/d3.v4.min.js"></script>
Upvotes: 2