Using Unicode superscripts to format ticks for a natural-log y-scale.
Last active
November 15, 2017 16:28
-
-
Save mbostock/7621155 to your computer and use it in GitHub Desktop.
Natural Log Scale
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> | |
.line { | |
fill: none; | |
stroke: steelblue; | |
stroke-width: 1.5px; | |
} | |
.axis--x text { | |
font: 10px sans-serif; | |
} | |
.axis--y text { | |
font: oblique 15px Georgia, serif; | |
} | |
.axis path, | |
.axis line { | |
fill: none; | |
stroke: #000; | |
shape-rendering: crispEdges; | |
} | |
</style> | |
<body> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script> | |
var superscript = "⁰¹²³⁴⁵⁶⁷⁸⁹", | |
formatPower = function(d) { return (d + "").split("").map(function(c) { return superscript[c]; }).join(""); }; | |
var margin = {top: 40.5, right: 40.5, bottom: 50.5, left: 60.5}, | |
width = 960 - margin.left - margin.right, | |
height = 500 - margin.top - margin.bottom; | |
var x = d3.scale.linear() | |
.domain([0, 100]) | |
.range([0, width]); | |
var y = d3.scale.log() | |
.base(Math.E) | |
.domain([Math.exp(0), Math.exp(9)]) | |
.range([height, 0]); | |
var xAxis = d3.svg.axis() | |
.scale(x) | |
.orient("bottom"); | |
var yAxis = d3.svg.axis() | |
.scale(y) | |
.orient("left") | |
.tickFormat(function(d) { return "e" + formatPower(Math.round(Math.log(d))); }); | |
var line = d3.svg.line() | |
.x(function(d) { return x(d[0]); }) | |
.y(function(d) { return y(d[1]); }); | |
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", "axis axis--y") | |
.attr("transform", "translate(-10,0)") | |
.call(yAxis); | |
svg.append("g") | |
.attr("class", "axis axis--x") | |
.attr("transform", "translate(0," + (height + 10) + ")") | |
.call(xAxis); | |
svg.append("path") | |
.datum(d3.range(100).map(function(x) { return [x, x * x + x + 1]; })) | |
.attr("class", "line") | |
.attr("d", line); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment