Reputation: 71
Using d3.js v4, how to show the special scale value which can't be divide exactly?
For example: set the domain([0,24]), set the ticks(3). The value 24 don't show in the axis.
Please tell me how to show the value.
var margin = {top: 10, right: 30, bottom: 30, left: 30},
width = 600 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var x = d3.scaleBand()
.rangeRound([0, width])
.domain(['A', 'B', 'C'])
.padding(0);
var y = d3.scaleLinear()
.domain([0, 24])
.range([height, 0]);
var xAxis = d3.axisBottom(x),
yAxis = d3.axisLeft(y).ticks(3);
var svg = d3.select('#chart')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.style('background-color', '#ecf0f1')
.append('g')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var g = svg.append('g');
g.append('g')
.attr('class', 'axis axis--x')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
g.append('g')
.attr('class', 'axis axis--y')
.call(yAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="chart"></svg>
Upvotes: 3
Views: 1050
Reputation: 102194
Use tickValues
, defining how many ticks you want with scale.ticks()
and pushing the first and last domain values by concatenation with scale.domain()
:
yAxis = d3.axisLeft(y)
.tickValues(y.ticks(3).concat(y.domain()));
Check the updated snippet:
var margin = {top: 10, right: 30, bottom: 30, left: 30},
width = 600 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var x = d3.scaleBand()
.rangeRound([0, width])
.domain(['A', 'B', 'C'])
.padding(0);
var y = d3.scaleLinear()
.domain([0, 24])
.range([height, 0]);
var xAxis = d3.axisBottom(x),
yAxis = d3.axisLeft(y)
.tickValues(y.ticks(3).concat(y.domain()));
var svg = d3.select('#chart')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.style('background-color', '#ecf0f1')
.append('g')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var g = svg.append('g');
g.append('g')
.attr('class', 'axis axis--x')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
g.append('g')
.attr('class', 'axis axis--y')
.call(yAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="chart"></svg>
Upvotes: 2