d3旋转文字标签

问题描述 投票:0回答:1

我有文字标签,我想旋转。

  in_years.selectAll(".xlabel")     
      .data(xTickLabels)
      .enter()
      .append("text")
      .attr("class","xlabel")
      .attr("text-anchor", "end") 
      //.attr("transform", "translate(0,0) rotate(-45)")
      .attr("font-size", "14px")
      .attr("x", (d,i) => xScale(xRange[i]))
      .attr("y", (d,i) => height+15)
      .text(function(d) { console.log(d);return d})
      ;

Wit“transform”一行评论我得到图1.取消注释我获得的图2,这对我来说没有意义。

有关为何会发生这种情况以及如何解决这个问题的任何提示我正在使用d3 v3这个enter image description here

enter image description here

d3.js axis-labels
1个回答
2
投票

为什么旋转效果不像你期望的那样是由于rotate()的css属性。 link

根据MDN doc中的rotate函数定义: ''旋转轴穿过原点''

因此,您必须翻译每个文本元素的(x,y),以使旋转轴与图形中的站点相关。

// this code, which each text will rotate according to (0,0)
svg.selectAll('text.norotation')
   .data(data)
   .enter()
   .append('text')
   .text((d)=>d)
   .classed('norotation', true)
   .attr('fill', 'black')
   .attr('x', (d,i)=> xScale(i))
   .attr('y', 200)

修改一个

//each text element will rotate according to its position
svg.selectAll('text.rotation')
   .data(data)
   .enter()
   .append('text')
   .text((d)=>d)
   .classed('rotation', true)
   .attr('fill', 'black')
   .attr('transform', (d,i)=>{
        return 'translate( '+xScale(i)+' , '+220+'),'+ 'rotate(45)';})
   .attr('x', 0)
   .attr('y', 0)

关于Observable的演示:qazxsw poi

© www.soinside.com 2019 - 2024. All rights reserved.