Home > Mobile >  How can i set each text label vertically in d3?
How can i set each text label vertically in d3?

Time:09-18

Please, have a look. I feel like i'm somewhere near,after searching stackoverflow. But still can set each label(it's date) vertically so it's readable.

https://codepen.io/DeanWinchester88/pen/XWgjjeW



const svg = d3.select("body")
  .append("svg")
  .attr("width",w)
  .attr("height",h)
  .attr("style", "outline: thin solid red;");
svg.selectAll("rect")
  .data(dataSet)
  .enter()
       .append("rect")
       .attr("x", (d,i) => i * 10)
       .attr("y", (d) =>  ( h - (d[1]/10  )  ) )
       .attr("width", 8)
       .attr("height", (d) => d[1] /10 )
       .attr("class", 'bar')
       .attr("data-date",(d) => d[0])
       .attr("data-gdp",(d) =>  d[1])
       .append("title")
       .text((d) => d)
  svg.selectAll("text")
       .data(dataSet)
       .enter()
       .append("text")
       .text((d) => d)
       .attr("x", (d,i) => i * 10)
       .attr("y", (d) =>  ( h - (d[1]/10  )  ))
      // .attr("transform", "rotate(-5)")
      .attr('transform', (d,i)=>{
       return 'translate( i  * 10, (d) =>  ( h - (d[1]/10  )  )) rotate(125)';})
      
});

CodePudding user response:

You can achieve this with just a little tweak. Instead of setting the x and y attribute, we can add that to the transform instead. So we move the object to the position that we want, then rotate it.

That is:

.attr("transform", (d,i) => "translate("   i*10   ","   (h-(d[1]/10))   "),rotate(90)");  

Remove the x and y lines before adding that.

That will show the text overlapping with the bars. To have the text above the bar we can just add:

.attr("text-anchor", "end")

You can also change the font-size, to ensure the text doesn't overlap with the other text:

text {
    font-size: 12px;
}

The final result is:

  • Related