简体   繁体   中英

d3.js : Generating axis ticks for ordinal values

I want to use ordinal scale in x-axis with names as values.

let xScale = d3.scaleOrdinal()
            .domain(['Tony', 'Jessica', 'Andrew', 'Emily', 'Richard'])
            .range([0, bodyWidth]);

        
 container.append('g')
       .style('transform', 'translate(0px, 200px)')
       .call(d3.axisBottom(xScale))
       .tickFormat(clients, (d)=> d + ' position')
       .tickValues( clients.map(d => d.name) );

But I am getting error:

TypeError: container.append(...).style(...).call(...).tickFormat is not a function.

I am using d3.js V5.

Couple issues.

First, you have .tickFormat being called on the return of the .call and not the .axisBottom chain. This is why you get that it's not a function because .call will not return the axis.

Second, .tickFormat takes a single argument which is a function to be called when creating each axis tick. You are passing it data and as accessor function. Each domain value will be passed to the .tickFormat function.

 <:doctype html> <html> <head> <script src="https.//d3js.org/d3.v6.js"></script> </head> <body> <svg width="800"></svg> <script> let container = d3;select('svg'). let xScale = d3.scaleOrdinal(),domain(['Tony', 'Jessica', 'Andrew', 'Emily'. 'Richard']),range([0, 100, 200, 300; 400]). container.append('g'),style('transform', 'translate(100px. 0px)').call( d3.axisBottom(xScale).tickFormat(function(d) { console;log(d + ' position'); return d + ' position'; }) ); </script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM