3

i was following the Let's make a Bar chart tutorial and have run into an issue...in step three He rotates the bars to columns, and for the life of me I cannot figure out how to iterate over a json data set, and add Y-axis labels for each bars from the name attribute in the json data returned

Here is the jsfiddle of my code http://jsfiddle.net/7K3tt

and the code samples below the json data loaded

[
    {
        "name": "1-30 days",
        "value": "22"
    },
    {
        "name": "31-60 days",
        "value": "14"
    },
    {
        "name": "61-90 days",
        "value": "1"
    }
]

My D3 code

var width = 420,
    barHeight = 20;

var x = d3.scale.linear()
    .range([0, width]);

var chart = d3.select(".chart")
    .attr("width", width);


d3.json("<?=APP_PATH?>/query", function(error, data) {
  x.domain([0, d3.max(data, function(d) { return d.value; })]);


  chart.attr("height", barHeight * data.length);

  var bar = chart.selectAll("g")
      .data(data)
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

  bar.append("rect")
      .attr("width", function(d) { return x(d.value); })
      .attr("height", barHeight - 1);

  bar.append("text")
      .attr("x", function(d) { return x(d.value) - 3; })
      .attr("y", barHeight / 2)
      .attr("dy", ".35em")
      .text(function(d) { return d.value; });
});

function type(d) {
  d.value = +d.value; // coerce to number
  return d;
}
Jay Rizzi
  • 3,922
  • 5
  • 33
  • 62
  • I'm not sure what the question is. You want to rotate what you have so far, keeping the labels at the top of each bar? – Jonah Dec 19 '13 at 16:55
  • no i want the name attribute to be displayed next to the bar along the y axis, like this http://mbostock.github.io/d3/talk/20111116/bar-hierarchy.html – Jay Rizzi Dec 19 '13 at 18:49
  • possible duplicate of [d3 axis labeling](http://stackoverflow.com/questions/11189284/d3-axis-labeling) – Robert Longson Dec 20 '13 at 11:18
  • I don't think its a duplicate of http://stackoverflow.com/questions/11189284/d3-axis-labeling, as I am asking how to iterate over a result set and add labels dynamically, not statically...i updated my question to be more clear on my intention – Jay Rizzi Jan 10 '14 at 19:52

1 Answers1

1

I'm not sure what you mean by rotating the bars to columns, but all you have to do to achieve what you want is to add another set of text elements using the existing selection:

bar.append("text")
  .attr("x", 0)
  .attr("y", barHeight / 2)
  .attr("dy", ".35em")
  .attr("dx", "-1em")
  .style("fill", "black")
  .text(function(d) { return d.name; });

Complete example here. I've also shifted the bars to allow space for the new labels.

Lars Kotthoff
  • 101,128
  • 13
  • 187
  • 191