typescript - Cannot set d3 axis to only integers -
i've looked @ couple of answers on here:
but they're not working me.
i have array of years, example:
years: array<number> = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]; let minxaxis = math.min(...this.years); let maxxaxis = math.max(...this.years); this.xscale = d3.scalelinear().range([this.margins.left, this.width - this.margins.right]).domain([minxaxis, maxxaxis]); this.xaxis = svg.append("g") .attr("class", "axis axis-x") .attr("transform", `translate(0, ${this.height - this.margins.bottom})`) .call(d3.axisbottom(this.xscale));
doing gives me following.
then when used .tickformat(d3.format("d"))
so:
this.xaxis = svg.append("g") .attr("class", "axis axis-x") .attr("transform", `translate(0, ${this.height - this.margins.bottom})`) // set display ticks digits .call(d3.axisbottom(this.xscale).tickformat(d3.format("d")));
i following
as can see, got rid of decimal, still lists duplicates, e.g 2011, 2011, ...
how fix x axis shows: 2010, 2011, 2012, ...?
there no duplicate in axis: values seem same because got rid of decimals.
the problem here simple: using wrong scale task. should use time scale or, if want treat years qualitative (categorical) variables, should use ordinal scale (like d3.scalepoint
) instead.
have in mind year not regular number: 2012
year, 2012.2412223
? if use linear scale treating years this: pure numbers.
therefore, solution dropping linear scale , using time scale (or ordinal scale).
however, if (for whatever reason) want stick linear scale , treat years numbers (which not), use tickvalues
make sure values in years
array show in axis:
d3.axisbottom(this.xscale) .tickvalues(years)
here demo:
var years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]; var svg = d3.select("svg"); var scale = d3.scalelinear() .domain(d3.extent(years)) .range([20, 480]); var axis = d3.axisbottom(scale) .tickvalues(years) .tickformat(d3.format("d")); var gx = svg.append("g") .attr("transform", "translate(0,50)"); axis(gx);
<script src="https://d3js.org/d3.v4.min.js"></script> <svg width="500" height="100"></svg>
Comments
Post a Comment