首页 > 解决方案 > D3 版本 5 自定义 x 轴值

问题描述

我正在尝试在 d3 v5 中获取自定义 x 轴值,我可以在网上找到的大多数示例似乎都是针对以前版本的,我现在对这些文档不太了解...

我正在用这样的对象制作条形图......

const data = {
  one: Math.floor(Math.random() * 100),
  two: Math.floor(Math.random() * 100),
  three: Math.floor(Math.random() * 100),
  four: Math.floor(Math.random() * 100),
}

所以我希望条形图的 x 轴值是字符串one, two, ...

我的 d3 代码对于刻度和轴看起来像这样

const keys = Object.keys(data);

let dataMax: number = 0;
keys.forEach(k => {
  if (data[k] > dataMax) {
    dataMax = data[k];
  }
});

const xScale = scaleLinear() // set the x scale and fit to width
  .domain([0, keys.length])
  .range([0, width]);

const yScale = scaleLinear()
  .domain([dataMax || 0, 0])
  .range([0, height]);

const s = select(this.node).select('.innerG');

s.append('g')
  .attr('class', 'xAxis') // set the class for the x axis
  .attr('transform', `translate(0, ${height})`)
  .call(axisBottom(xScale)); // add the axis

s.append('g')
  .attr('class', 'yAxis') // set the class for the y axis
  .call(axisLeft(yScale)); // set the axis

有了这个,我的图表渲染得很好,但我得到1, 2, ...的是 x 轴,而不是我的字符串数据键。我在网上找到的大多数示例都说要使用tickFormat()svg.axis(),但这似乎是 D3 的旧版本。如何使用当前的 v5 做到这一点?

标签: javascriptd3.js

解决方案


推荐阅读