S.BM S.BM - 5 months ago 43
CSS Question

dc.js heatmap how to rotate text ?

how to select and rotate the texts of the x axis only !
In this Example :
http://dc-js.github.io/dc.js/examples/heat.html

So select from 1 to 20 and rotate them !

I tried this way :

chart
.selectAll("g.cols.axis > text")
.attr("text-anchor", "middle")
.attr("transform", function () {
return "rotate(-20)"
})
.style("fill", "blue");


but it seems that I'am selecting the whole X-axis and not every text separatly .
The fill style works fine but the transformation does not work properly and the axe is entirely rotated.

Answer

You must rotate each text element on X Axis around its own center. To do that you must specified the rotation angle AND the center of rotation

rotate(angle centerX centerY)

With that on mind, you can do:

  chart.selectAll('g.cols.axis > text')
            .attr('transform', function (d) {
                var coord = this.getBBox();
                var x = coord.x + (coord.width/2),
                    y = coord.y + (coord.height/2);
                return "rotate(-20 "+x+" "+y+")"
                });

Remember do it after call to chart.render(); or your selection will be empty

If you want understand why this, take a look at: https://sarasoueidan.com/blog/svg-transformations/

Here the working code