Skip to content

Instantly share code, notes, and snippets.

@tomgp
Created December 18, 2014 14:16
Show Gist options
  • Save tomgp/56e390b8619c069bc03b to your computer and use it in GitHub Desktop.
Save tomgp/56e390b8619c069bc03b to your computer and use it in GitHub Desktop.
very simple tick formatter

A small exampe of how you can make your tick labels display as you'd like them to.

note D3 can provide its own formatter fuctions for common cases here

<html>
<head>
<title>tick format example</title>
<style type="text/css">
svg{font-family: sans-serif;}
.domain{fill:none; stroke:#000;}
.tick, line{stroke:#000;}
.tick, text{stroke:none;}
</style>
</head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<body>
</body>
<script type="text/javascript">
//make a scale
var xScale = d3.scale.linear()
.range([0, 500])
.domain([-0.5, 0.5]);
//make an axis
var myAxis = d3.svg.axis()
.scale( xScale ) //based on the scale we just made
.tickFormat(neatDecimal); //give it a tickFormat, a function which tells the scale how to display the tick values
function neatDecimal(number){
if(number == 0){ //if the number is zero, return it without any decimal places
return 'O'; //i've changed it to an 'O'
}
//otherwise just leave it as is
return number;
}
//then lets attach it to the page...
d3.select('body')
.append('svg').attr({height:100, width:700}).append('g').attr('transform','translate(100,0)')
.call(myAxis)
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment