d3 axis labeling

后端 未结 6 1208
天涯浪人
天涯浪人 2020-12-12 15:55

How do I add text labels to axes in d3?

For instance, I have a simple line graph with an x and y axis.

On my x-axis, I have ticks from 1 to 10. I want the wo

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 16:44

    If you want the y-axis label in the middle of the y-axis like I did:

    1. Rotate text 90 degrees with text-anchor middle
    2. Translate the text by its midpoint
      • x position: to prevent overlap of y-axis tick labels (-50)
      • y position: to match the midpoint of the y-axis (chartHeight / 2)

    Code sample:

    var axisLabelX = -50;
    var axisLabelY = chartHeight / 2;
    
    chartArea
        .append('g')
        .attr('transform', 'translate(' + axisLabelX + ', ' + axisLabelY + ')')
        .append('text')
        .attr('text-anchor', 'middle')
        .attr('transform', 'rotate(-90)')
        .text('Y Axis Label')
        ;
    

    This prevents rotating the whole coordinate system as mentioned by lubar above.

提交回复
热议问题