如何在轴上显示结束刻度值?

时间:2016-11-22 02:47:18

标签: d3.js

使用d3.js v4,如何显示不能精确划分的特殊刻度值?

例如:设置域([0,24]),设置滴答(3)。值24不显示在轴上。

请告诉我如何显示价值。

enter image description here

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>

1 个答案:

答案 0 :(得分:2)

使用tickValues,使用scale.ticks()定义所需的滴答数,并通过与scale.domain()串联推送第一个和最后一个域值:

yAxis = d3.axisLeft(y)
    .tickValues(y.ticks(3).concat(y.domain()));

检查更新的代码段:

&#13;
&#13;
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);
&#13;
<script src="https://d3js.org/d3.v4.min.js"></script>

<svg id="chart"></svg>
&#13;
&#13;
&#13;