Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

javascript - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...