Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you change the last tick value in D3.js?

Say I have something like this:

|------|------|------|------|------|------|------|------|
0      10     20     30     40     50     60     70     80

How can I change the last value

80

to

> 80

I've tried,

.tickValues();

editing

.domain()

etc.

like image 901
rotaercz Avatar asked Jul 19 '17 21:07

rotaercz


2 Answers

You need to use .tickFormat to change tick text. The easiest way to do this is to check to see if the datum for a particular tick is equal to 80, as shown below, and modify that tick.

Note however, d3 tries to optomize ticks, this check won't work if d3 decides it doesn't want a tick at 80, in which case using .tickValues can ensure that a tick is at the value you want to change.

var width = 300;
var height = 200;

var svg = d3.select("body")
  .append("svg")
  .attr("width",width+40)
  .attr("height",height)
  .attr("transform","translate(20,20)"); 

var x = d3.scaleLinear()
  .domain([0,80])
  .range([0,width]);
  
var xAxis = d3.axisBottom(x)
   .tickValues([0,20,30,40,50,60,70,80])
   .tickFormat(function(d) { return (d == 80) ? "> 80" : d; })
    
svg.call(xAxis);
  
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>
like image 127
Andrew Reid Avatar answered Sep 30 '22 08:09

Andrew Reid


This can be done checking if the tick is the last one using the second and third arguments:

var axis = d3.axisBottom(scale)
    .tickFormat(function(d, i, n) {
        return n[i + 1] ? d : ">" + d;
    })

Since there is no element at n[i + 1] the last index will return false.

Then, the ternary ensures that you apply whatever change you want to the last tick only, regardless its value.

Here is the demo:

var svg = d3.select("svg");
var scale = d3.scaleLinear()
  .range([20, 480])
  .domain([0, 80]);

var axis = d3.axisBottom(scale)
  .tickFormat(function(d, i, n) {
    return n[i + 1] ? d : ">" + d;
  })

var gX = svg.append("g")
  .attr("transform", "translate(0,50)")
  .call(axis)
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="100"></svg>
like image 31
Gerardo Furtado Avatar answered Sep 27 '22 08:09

Gerardo Furtado