0

I am trying to add text on each bar in grouped bar chart. but it is not showing & no error is there on console. I am using the sample code from https://bl.ocks.org/bricedev/0d95074b6d83a77dc3ad

I tried below code:

<!DOCTYPE html>
<meta charset="utf-8">
<head>
    <style>
        body {
          font: 10px sans-serif;
        }
        .axis path,
        .axis line {
          fill: none;
          stroke: #000;
          shape-rendering: crispEdges;
        }

        .x.axis path {
          //display: none;   //to show x axis
        }
    </style>
</head>

<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 40, right: 60, bottom: 40, left: 40},
    width = 560 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

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

var x1 = d3.scale.ordinal();

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

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

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var color = d3.scale.ordinal()
    .range(["#ca0020","#f4a582","#d5d5d5","#92c5de","#0571b0"]);

var svg = d3.select('body').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("data.json", function(error, data) {

  var categoriesNames = data.map(function(d) { return d.categorie; });
  var rateNames = data[0].values.map(function(d) { return d.rate; });

  x0.domain(categoriesNames);
  x1.domain(rateNames).rangeRoundBands([0, x0.rangeBand()]);
  y.domain([0, d3.max(data, function(categorie) { return d3.max(categorie.values, function(d) { return d.value; }); })]);

    //Graph Title
    svg.append("text")
       .attr("transform", "translate(100,0)")
       .attr("x", 100)
       .attr("y", -20)
       .attr("font-size", "24px")
       .text("Grouped Bar Chart");

    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
      .append("text")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .style('font-weight','bold')
      .attr("transform", "translate(" + width + ",10)")
      .text("Months");

    svg.append("g")
      .attr("class", "y axis")
      .style('opacity','0')
      .call(yAxis)
      .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .style('font-weight','bold')
      .text("Incidents");

    svg.select('.y').transition().duration(500).delay(1300).style('opacity','1');

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

    //draw bars 
    slice.selectAll("rect")
      .data(function(d) { return d.values; })
      .enter().append("rect")
      .attr("width", x1.rangeBand())
      .attr("x", function(d) { return x1(d.rate); })
      .style("fill", function(d) { return color(d.rate) })
      .attr("y", function(d) { return y(0); })
      .attr("height", function(d) { return height - y(0); })
      .on("mouseover", function(d) {
          d3.select(this).style("fill", d3.rgb(color(d.rate)).darker(2));  
      })
      .on("mouseout", function(d) {
          d3.select(this).style("fill", color(d.rate));
      });

    slice.selectAll("text")
        .data(function(d) {return d.values ;})
        .enter()
        .append("text") 
        .attr("x", function(d) { return x1(d.rate); })
        .attr("y", function(d) { return ( y(0) ) ; })
        .text(function(d) {
           return  (d.value);  // Value of the text
         });

    slice.selectAll("rect")
      .transition()
      .delay(function (d) {return Math.random()*1000;})
      .duration(1000)
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); });


  //Legend
  var legend = svg.selectAll(".legend")
      .data(data[0].values.map(function(d) { return d.rate; }).reverse())
  .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d,i) { return "translate(60," + i * 20 + ")"; })
      .style("opacity","0");

  legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", function(d) { return color(d); });

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) {return d; });

  legend.transition().duration(500).delay(function(d,i){ return 1300 + 100 * i; }).style("opacity","1");

});

</script>
</body>
</html>

But the output is output after adding block

It is showing object object in output. Please help.

output of code is here

  • It looks like you are [converting an array to a string](https://stackoverflow.com/questions/4750225/what-does-object-object-mean). Can you be more specific about what you want the `` to say? For example, are you trying to label each bar, or each group? If it's the former, how about trying `return d.value` in the `.text`? – mdml Dec 10 '19 at 13:42

1 Answers1

0

You're appending to slice, which is a selection of all the bar groups, not the bars themselves. Try something like this to get started:

  slice.selectAll("text")
      .data(function(d) { return d.values; })
      .enter().append("text")
      .attr("x", function(d) { return x1(d.rate); })
      .attr("y", function(d) { return y(d.value); })
      .text(function(d) { return d.value })
SmokeyShakers
  • 3,372
  • 1
  • 7
  • 18
  • Thanks a lot. This code worked. But the y coordinate of text is not set properly.I want to set the text above bars. I tried same as height & y coordinate given in drawing the bars. But it is not coming at the right place. I have added the whole code in question. – Priyanshu shukla Dec 11 '19 at 07:53
  • You have `.attr("y", function(d) { return ( y(0) ) ; })`. That's the baseline of the chart. `.attr("y", function(d) { return y(d.value); })` is the top of the rectangle. – SmokeyShakers Dec 11 '19 at 14:04