1

I'm workng with d3.js and don't haveso many experiences with it. I have a grouped bar chart with the values written on each bar (horizontal). How can I rotate them so that they are vertical (rotated 90°)? My code:

bars.append("text")
      .attr("x", function(d) { return x(d.name); })
      .attr("y", function(d) { return y0(d.value1) + 3; })
      .attr("dy", ".75em")
      .text(function(d) { return d.value1; });

       bars.append("text")
      .attr("x", function(d) { return x(d.name) + barWidth / (2.25); })
      .attr("y", function(d) { return y1(d.value2) + 3; })
      .attr("dy", ".75em")
      .text(function(d) { return d.value2; });

       bars.append("text")
     .attr("x", function(d) { return x(d.name) + barWidth / (4.0); })
      .attr("y", function(d) { return y2(d.value3) + 3; })
      .attr("dy", ".75em")
      .text(function(d) { return d.value3; });

       bars.append("text")
     .attr("x", function(d) { return x(d.name) + barWidth / (1.5); })
      .attr("y", function(d) { return y3(d.value4) + 3; })
      .attr("dy", ".75em")
       .text(function(d) { return d.value4; });
VividD
  • 10,456
  • 6
  • 64
  • 111
user3346326
  • 137
  • 1
  • 7

2 Answers2

1

Take a look at my answer to a similar question.

I believe you are coming across the same problem as described in the linked answer (and in the question itself) - your rotation is around a corner of a bar, not around the center! And that's why labels disappear!

Just want to highlight what was the solution to the linked problem: use a composite transformation that consists of a translation and a rotation. The code from example looks like this: (and yours should look similar; you just have to understand the code from linked jsfiddles before you apply the same strategy to your situation)

  node.selectAll("text.nodeValue")
      .text(function (d) { return formatNumber(d.value); })
      .attr("text-anchor", "middle")
      .attr("transform", function (d) {
           return "rotate(-90) translate(" +
                       (-d.dy / 2) +
                       ", " +
                       (sankey.nodeWidth() / 2 + 5) +
       ")";});

Before/after pictures:

BEFORE

enter image description here

AFTER

enter image description here

Community
  • 1
  • 1
VividD
  • 10,456
  • 6
  • 64
  • 111
0

In svg it is quite easy to move/rotate an element using the transform attribute. Hence you can do (as suggested by Lars Kotthoff):

bars.selectAll("text").attr("transform","rotate(90)")

Also, from the code you posted, I would recommend you to have a look at selections in order to not generate each bar legend by hand. This tutorial can help you for this: Let's Make a Bar Chart

Christopher Chiche
  • 15,075
  • 9
  • 59
  • 98
  • when I try this the labels just disappear. I think that I could solve this by using `.attr("transform","rotate(90) translate(?)")` - am I right? But then I don't know what to write in the brackets of translate. – user3346326 Jul 16 '14 at 16:15