更改D3分组图表中x轴(序数)刻度值的值

时间:2014-11-20 08:18:31

标签: javascript d3.js

我有一个D3分组条形图,x轴使用我的x0刻度形成,其中域为数据值。由于域具有数据值,因此我的刻度文本也是相同的数据值。我想将刻度值更改为数据名称,保持我的比例不变,因为名称可以相同但数据值是唯一的。 请帮我改变刻度值。

e.g。名称:'新泽西',       值: '[日历]&安培;新泽西州' 我希望使用值来创建轴,但是刻度文本应该是名称。

http://jsfiddle.net/pragyan88/681q7umb/6

var data = {
  chartTitle: "PopulationByState",
  xAxisLabel: "State",
  yAxisLabel: "Population",
  series: [{
    name: "< 5 Years",
    longName: "Age less than 5 Years",
    value: "i",
    data: [2704659, 2027307, 1208495, 894368, 3157759]
  }, {
    name: "5-13 Years",
    longName: "Age between 5 to 13 years",
    value: "i",
    data: [4704659, 6027307, 808495, 1094368, 2157759]
  }, {
    name: "14-20 Years",
    longName: "Age between 14 to 20 years",
    value: "i",
    data: [1104659, 8027307, 1008495, 394368, 1157759]
  }, {
    name: "21-40 Years",
    longName: "Age between 21 to 40 years",
    value: "i",
    data: [1404659, 2027307, 4208495, 6027307, 5157759]
  }, {
    name: "41-65 Years",
    longName: "Age between 41 to 65 years",
    value: "i",
    data: [2404659, 3027307, 7208495, 8027307, 6157759]
  }, {
    name: ">65 Years",
    longName: "Age greater than 65 years",
    value: "i",
    data: [1404659, 9027307, 4208495, 10027307, 5157759]
  }],

  categories: [{
    name: 'CA',
    longName: 'California',
    value: '[Calendar]&California'
  }, {
    name: "TX",
    longName: 'Texas',
    value: '[Calendar]&Texas'
  }, {
    name: 'NY',
    longName: 'New York',
    value: '[Calendar]&NewYork'
  }, {
    name: "FL",
    longName: 'Florida',
    value: '[Calendar]&Florida'
  }, {
    name: "NJ",
    longName: 'New Jersey',
    value: '[Calendar]&NewJersey'
  }]
}


var format = d3.format('.2s');

var returnArray = [];

var canvasWidth = document.getElementById("chart").offsetWidth,
  canvasHeight = document.getElementById("chart").offsetHeight;

var margin = {
    top: 80,
    right: 10,
    bottom: 60,
    left: 30
  },
  width = canvasWidth - margin.left - margin.right,
  height = canvasHeight - margin.top - margin.bottom;

var x0 = d3.scale.ordinal()
  .rangeRoundBands([0, width], 0.1, 0.2);

var x1 = d3.scale.ordinal();

var y = d3.scale.linear()
  .range([height, 0]);

var color = ['rgb(218,165,32)', 'rgb(41,95,72)', 'rgb(82,82,20)', 'rgb(43,33,6)', 'rgb(96,35,32)', 'rgb(54,69,79)'];


var xAxis = d3.svg.axis()
  .scale(x0)
  .orient("bottom")
  .tickSize(-height, 0, 0);

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left")
  .tickFormat(d3.format(".2s"))
  .tickSize(-width, 0, 0);

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "data: <span style='color:green;'>" + d.data[d.index] + "</span><br/>" + "series: <span style='color:yellow;'>" + d.seriesLongName + "</span><br/>" + "category: <span style='color:red;'>" + data.categories[d.index].longName + "</span>";
  });

var legendTip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<span style='color:green;'>" + d.longName + "</span>";
  });

var svg = d3.select("#chart").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 + ")");


for (var i = 0; i < data.series.length; i++) {

  var rgbColor = d3.rgb(color[i]);
  var rgbLighterColor = d3.rgb(color[i]).brighter(4);
  var id = 'gradient' + i;
  var gradient = svg.append("svg:defs")
    .append("svg:linearGradient")
    .attr('id', id)
    .attr("x1", "0%")
    .attr("y1", "0%")
    .attr("x2", "100%")
    .attr("y2", "100%");

  gradient
    .append("stop")
    .attr("offset", "0%")
    .attr("stop-color", rgbLighterColor)

  gradient
    .append("stop")
    .attr("offset", "100%")
    .attr("stop-color", rgbColor)
}


svg.call(tip);
svg.call(legendTip);

x0.domain(data.categories.map(function(d) {
  return d.name;
}));
x1.domain(data.series.map(function(d) {
  return d.name
})).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data.series, function(d) {
  return d3.max(d.data);
})]);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("y", 15)
  .attr("x", -15)
  .style("text-anchor", "end")
  .attr("transform", "rotate(-90)")
  .attr('class', 'chartLabel')
  .text(data.yAxisLabel)

var state = svg.selectAll(".state")
  .data(data.categories)
  .enter().append("g")
  .attr("class", "state")
  .attr("transform", function(d) {
    return "translate(" + x0(d.name) + ",0)";
  });

var bars = state.selectAll("rect")
  .data(function(d, i) {
    var rArray = [];
    for (var x = 0; x < data.series.length; x++) {
      rArray.push({
        name: data.series[x].name,
        data: data.series[x].data,
        index: i,
        seriesLongName: data.series[x].longName
      });
    }

    return rArray;
  })
  .enter().append("rect")
  .on('click', function(d) {
    if (d3.event.ctrlKey) {
      if (d3.select(this).style('opacity') == 1) {
        returnArray.push({
          categoryName: data.categories[d.index].name,
          seriesName: d.name,
          data: d.data[d.index]
        });
        d3.select(this).style('opacity', 0.5);
      } else {
        returnArray.forEach(function(obj, i) {
          if (obj.categoryName == data.categories[d.index].name && obj.seriesName == d.name && obj.data == d.data[d.index])
            returnArray.splice(i, 1);
        });
        d3.select(this).style('opacity', 1);
      }
    } else {
      var rect = svg.selectAll('rect');
      rect.forEach(function(rec) {
        rec.forEach(function(r) {
          returnArray = [];
          r.style.opacity = 1;
        })
      });
      if (d3.select(this).style('opacity') == 1) {
        d3.select(this).style('opacity', 0.5);
        returnArray.push({
          categoryName: data.categories[d.index].name,
          seriesName: d.name,
          data: d.data[d.index]
        });
      }
    }

  })
  .on('contextmenu', function(d) {
    d3.event.preventDefault();
    alert(d.name);
  })
  .on('mouseover', tip.show)
  .on('mouseout', tip.hide)
  .attr('class', 'bar')
  .attr("width", x1.rangeBand())
  .attr("x", function(d) {
    return x1(d.name);
  })
  .attr("y", height)
  .attr("height", 0)
  .style("fill", function(d, i) {
    return "url(#gradient" + i + ")"
  });


bars.transition()
  .attr('y', function(d) {
    return y(d.data[d.index]);
  })
  .attr('height', function(d) {
    return height - y(d.data[d.index]);
  })
  .delay(function(d, i) {
    return i * 250;
  }).ease('elastic');


svg.append("text")
  .attr("transform", "translate(" + (width / 2) + " ," + (height + margin.bottom / 2) + ")")
  .style("text-anchor", "middle")
  .attr('class', 'chartLabel')
  .text(data.xAxisLabel);

svg.append("text")
  .attr("transform", "translate(" + (width / 2) + " ," + "0)")
  .style("text-anchor", "middle")
  .attr('class', 'chartTitle')
  .text(data.chartTitle);


d3.select("svg").on('contextmenu', function() {
  var d3_target = d3.select(d3.event.target);
  if (!d3_target.classed("bar")) {
    d3.event.preventDefault();
    alert('I m the body!!')
  }
});

d3.select("svg").on('click', function() {
  var d3_target = d3.select(d3.event.target);
  if (!(d3_target.classed("bar") || d3_target.classed("legend"))) {
    returnArray = [];
    var rect = svg.selectAll('rect');
    rect.forEach(function(rec) {
      rec.forEach(function(r) {
        r.style.opacity = 1;
      })
    });
  }
});
body {
  font: 10px sans-serif;
}
.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}
.bar {
  fill: steelblue;
}
.x.axis path {
  display: none;
}
<section class="container">
  <div class='watermark'>
    <div id="chart" style="width:300px;height:400px;"></div>
  </div>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

/

提前致谢。

1 个答案:

答案 0 :(得分:2)

根据所讨论的输入数据的json结构,使用x轴的以下行有助于:

&#13;
&#13;
svg.append("g")
.attr("class", "x axis")
.attr("id", "xaxis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll('text')
.text(function (d,i) {
   return data.categories[i].name;
})
&#13;
&#13;
&#13;