This example demonstrates how to rotate axis labels by 90° using post-selection. After the axis is rendered, the text label elements are selected, and then attributes on the elements are modified to customize the label appearance.
Last active
July 9, 2024 18:55
-
-
Save mbostock/4403522 to your computer and use it in GitHub Desktop.
Rotated Axis Labels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.axis text { | |
font: 10px sans-serif; | |
} | |
.axis line, | |
.axis path { | |
fill: none; | |
stroke: #000; | |
shape-rendering: crispEdges; | |
} | |
</style> | |
<body> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script> | |
var margin = {top: 250, right: 40, bottom: 250, left: 40}, | |
width = 960 - margin.left - margin.right, | |
height = 500 - margin.top - margin.bottom; | |
var x = d3.time.scale() | |
.domain([new Date(2012, 0, 1), new Date(2013, 0, 1)]) | |
.range([0, width]); | |
var xAxis = d3.svg.axis() | |
.scale(x); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width + margin.left + margin.right) | |
.attr("height", height + margin.top + margin.bottom) | |
.append("g") | |
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); | |
svg.append("g") | |
.attr("class", "x axis") | |
.attr("transform", "translate(0," + height + ")") | |
.call(xAxis) | |
.selectAll("text") | |
.attr("y", 0) | |
.attr("x", 9) | |
.attr("dy", ".35em") | |
.attr("transform", "rotate(90)") | |
.style("text-anchor", "start"); | |
</script> |
alternatively, to achieve rotate(-90)
:
.selectAll("text")
.style("text-anchor", "start")
.style("writing-mode", "sideways-lr");
but sideways-*
is supported by Firefox only ... a work-around for all browsers:
.selectAll("text")
.style("text-anchor", "end")
.style("writing-mode", "vertical-rl")
.style("transform", `rotate(180deg)`);
again needs some tuning of the final position ...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
simpler & robust with regards to text sizing: