knee pain
knee pain

Reputation: 620

Add text to outer ticks of a D3 axis

When creating a basic axis using d3, it seems that d3 is doing a nice job of choosing what ticks and values to display. When I have a domain with ugly values (e.g 4.4 instead of 0), it will not display any text for the outer ticks, as intended.

My question is, how can I add some custom text for the outer ticks? (or maybe in the left and right sides of the axis, not necessarily bellow it)

var scale = d3.scaleLinear().domain([4.4, 989.4]).range([0, 600]);

var axis = d3.axisBottom().scale(scale);

d3.select('.axis')
	.call(axis);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
	<svg width="650" height="40">
		<g class="axis" transform="translate(20, 0)" />
	</svg>

Upvotes: 3

Views: 739

Answers (1)

Mikhail Shabrikov
Mikhail Shabrikov

Reputation: 8509

You can force d3 to show outer ticks using .nice method. Excerpt from the documentation:

Extends the domain so that it starts and ends on nice round values. This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value.

var scale = d3.scaleLinear().domain([4.4, 989.4]).range([0, 600]).nice();

var axis = d3.axisBottom().scale(scale);

d3.select('.axis')
	.call(axis);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
	<svg width="650" height="40">
		<g class="axis" transform="translate(20, 0)" />
	</svg>

You also can set tickValues for your axis this way (in this case scale domain will not be modified):

var scale = d3.scaleLinear().domain([4.4, 989.4]).range([0, 600]);

var tickValues= [].concat(scale.domain()[0], scale.ticks(), scale.domain()[1]);

var axis = d3.axisBottom().scale(scale).tickValues(tickValues);

d3.select('.axis')
	.call(axis);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
	<svg width="650" height="40">
		<g class="axis" transform="translate(20, 0)" />
	</svg>

Upvotes: 2

Related Questions