d3 axis labeling d3 axis labeling javascript javascript

d3 axis labeling


Axis labels aren't built-in to D3's axis component, but you can add labels yourself simply by adding an SVG text element. A good example of this is my recreation of Gapminderā€™s animated bubble chart, The Wealth & Health of Nations. The x-axis label looks like this:

svg.append("text")    .attr("class", "x label")    .attr("text-anchor", "end")    .attr("x", width)    .attr("y", height - 6)    .text("income per capita, inflation-adjusted (dollars)");

And the y-axis label like this:

svg.append("text")    .attr("class", "y label")    .attr("text-anchor", "end")    .attr("y", 6)    .attr("dy", ".75em")    .attr("transform", "rotate(-90)")    .text("life expectancy (years)");

You can also use a stylesheet to style these labels as you like, either together (.label) or individually (.x.label, .y.label).


In the new D3js version (version 3 onwards), when you create a chart axis via d3.svg.axis() function you have access to two methods called tickValues and tickFormat which are built-in inside the function so that you can specifies which values you need the ticks for and in what format you want the text to appear:

var formatAxis = d3.format("  0");var axis = d3.svg.axis()        .scale(xScale)        .tickFormat(formatAxis)        .ticks(3)        .tickValues([100, 200, 300]) //specify an array here for values        .orient("bottom");


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.