score:2

Accepted answer

For showing the background for the bars, just copy your selection and chose a value of 100% for the rectangles, in a light gray fill:

var backgroundBar = svg.selectAll(null)
    .data(data)
    .enter()
    .append("rect")
    //etc...
    .attr("width", function(d) {
        return x(100);
    });

Of course, you'll have to change the domain of the x scale:

var x = d3.scaleLinear()
    .domain([0, 100]);

Then, drop both axis and print the labels using a text selection.

Finally, use another text selection for the values:

var values = svg.selectAll(null)
    .data(data)
    .enter()
    .append("text")
    //etc...
    .text(function(d) {
        return +d.xAxis
    })

If you want, you can tween the text:

.attrTween("text", function(d) {
    var self = this
    var i = d3.interpolateNumber(0, +d.xAxis);
    return function(t) {
        return d3.select(self).text(~~i(t));
    }
});

This is the result:

var data = [{
  "yAxis": "score",
  "xAxis": "72"
}];

var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 80
  },
  width = 500 - margin.left - margin.right,
  height = 200 - margin.top - margin.bottom;

var y = d3.scaleBand()
  .range([height, 0])
  .padding(0.4);

var x = d3.scaleLinear()
  .range([0, width])
  .domain([0, 100]);

var svg = d3.select("body").append("svg")
  .attr("width", 500)
  .attr("height", 200)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

y.domain(data.map(function(d) {
  return d.yAxis;
}));

var backgroundBar = svg.selectAll(null)
  .data(data)
  .enter()
  .append("rect")
  .attr("fill", "lightgray")
  .attr("y", function(d) {
    return y(d.yAxis);
  })
  .attr("height", y.bandwidth())
  .attr("width", function(d) {
    return x(100);
  });

var bar = svg.selectAll(null)
  .data(data)
  .enter()
  .append("rect")
  .attr("class", "bar")
  .attr("y", function(d) {
    return y(d.yAxis);
  })
  .attr("height", y.bandwidth())
  .transition()
  .duration(2000)
  .delay(function(d, i) {
    return i * 100
  })
  .attr("width", function(d) {
    return x(d.xAxis);
  });

var labels = svg.selectAll(null)
  .data(data)
  .enter()
  .append("text")
  .attr("y", function(d) {
    return y(d.yAxis) + y.bandwidth() / 2;
  })
  .attr("x", -10)
  .attr("text-anchor", "end")
  .text(function(d) {
    return d.yAxis
  });

var values = svg.selectAll(null)
  .data(data)
  .enter()
  .append("text")
  .attr("y", function(d) {
    return y(d.yAxis) + y.bandwidth() / 2;
  })
  .attr("x", 10)
  .text(function(d) {
    return +d.xAxis
  })
  .transition()
  .duration(2000)
  .delay(function(d, i) {
    return i * 100
  })
  .attr("x", function(d) {
    return x(d.xAxis) + 10;
  })
  .attrTween("text", function(d) {
    var self = this
    var i = d3.interpolateNumber(0, +d.xAxis);
    return function(t) {
      return d3.select(self).text(~~i(t));
    }
  });
<script src="https://d3js.org/d3.v4.min.js"></script>


Related Query