我有一个Json数据看起来像这样:

[
  {
    "year": 2002,
    "gender": 2,
    "age": 8,
    "population": 0
  },
  {
    "year": 2002,
    "gender": 2,
    "age": 17,
    "population": 25
  },
  {
    "year": 2002,
    "gender": 2,
    "age": 18,
    "population": 291
  },
  {
    "year": 2002,
    "gender": 2,
    "age": 23,
    "population": 375
  },
  {
    "year": 2002,
    "gender": 2,
    "age": 26,
    "population": 212
  },
  {
    "year": 2002,
    "gender": 2,
    "age": 29,
    "population": 108
  },
  {
    "year": 2002,
    "gender": 2,
    "age": 38,
    "population": 74
  },
  {
    "year": 2002,
    "gender": 2,
    "age": 47,
    "population": 0
  },
  {
    "year": 2002,
    "gender": 2,
    "age": 48,
    "population": 0
  },


我的代码现在在xScale中返回d.age,因此X轴的标签与数据相同。下面是我现在的图表:

javascript - 如何自定义X轴的标签,这意味着X轴的标签与数据不同-LMLPHP

但是,我想自定义x轴的标签,我想设为“ 0--8”,“ 9--17”,“ 18--20”,“ 21--23”,“ 24-- 26“,” 27--29“,” 30--38“,” 39--47“,” 48+“,如下图所示:
javascript - 如何自定义X轴的标签,这意味着X轴的标签与数据不同-LMLPHP

下面是现在的代码:

var margin = {top:0, right: 30, bottom: 50, left: 60},
            width = 600 - margin.left - margin.right,
            height = 600 - margin.top - margin.bottom;

state = {year: 2002, gender: 2};


var svg = d3.select('#main')
       .append("svg")
       .attr('width', width + margin.left + margin.right)
       .attr('height', height + margin.top + margin.bottom)
       .append("g")
       .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

d3.json('./years3.json').then(years => {


var ageDomain = unique(years.map(row => row.age));
//var age = ["0--8", "9--17", "18--20", "21--23", "24--26", "27--29", "30--38", "39--47", "48+"]

//var xScale = d3.scalePoint()
            //.range([0, width])
            //.domain(age)
            //.padding(0.2);

var xScale = d3.scaleBand().rangeRound([0, width])
  .padding(0.1)
  .domain(ageDomain);



svg.append("g")
   .attr("transform", "translate(0," + height + ")")
   .call(d3.axisBottom(xScale))
   .selectAll("text")
   .attr("transform", "translate(-10,0)rotate(-45")
   .style("text-anchor", "end");

var peopleDomain = [0, d3.max(years, row => row.population)];

var yScale = d3.scaleLinear()
             .range([height, 0])
             .domain(peopleDomain);

svg.append("g")
   .call(d3.axisLeft(yScale));

最佳答案

添加以下功能:

const getRange = d => {
    const index = ageDomain.findIndex(item => item === d);
    if(index === 0)
        return `0 -- ${d}`;
    else
        return `${ageDomain[index-1] + 1} -- ${d}`;
}


然后,在创建底轴时,添加以下行

.text(d => getRange(d))



.selectAll(“ text”):

svg.append("g")
   .attr("transform", "translate(0," + height + ")")
   .call(d3.axisBottom(xScale))
   .selectAll("text")
   .text(d => getRange(d))
   .attr("transform", "translate(-10,0)rotate(-45")
   .style("text-anchor", "end");

10-06 12:15