简体   繁体   中英

Rotate label text on D3

Im creating a mekko chart and wanted to rotate the legends on x axis.

Example of what i did: https://codepen.io/fabioTester/pen/JjYeJEv

I want to rotate the elements with class "labelTitle" on the example...

I tried using the following code to rotate:

        // rotation code
        svg.selectAll(".month .labelTitle")
            .attr("transform", function (d) {
                return "translate(0) rotate(-25)"

            });

I'm guessing my issue is the calculation of the translate, but can't figure out how to fix it.

Thanks in advance for any suggestions.

I noticed the labels seem to rotate around a point that is quite far away from their actual position, so a small increase in rotation would quickly rotate them out of sight.

If you set the transform-origin of every individual label to its x and y position, it will rotate the individual labels around that point instead.

svg
  .selectAll(".month")
  .append("text")
  .text(function (d) {
    return d.key;
  })
  .attr("x", 5)
  .attr("y", function (d) {
    return height - (margin * 2);
  })
  .attr('transform-origin', `5 ${height - (margin * 2)}`)
  .attr("class", "labelTitle");
svg.selectAll('.labelTitle')
  .attr('transform', d => 'translate(0, 10), rotate(25)')

I also noticed the y -value of your labels didn't respect the margin, so I fixed that as well.

I came up with the following codepen: https://codepen.io/pitchblackcat/pen/OJyawaV

It seems like you forgot to append deg to rotate's value.

Try this:

// rotation code
svg.selectAll(".month .labelTitle")
  .attr("transform", function (d) {
     return "translate(0) rotate(-25deg)"
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM