javascript - 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 做到这一点?
解决方案
推荐阅读
- javascript - 如何在方法运行时更新 DOM?
- angular - 离子:“Http”已声明但从未使用过
- tomcat - 旧 Tomcat 环境在 Jelastic Platform 5.4 版上失败
- bash - history -c 不会将 $HISTCMD 重置为 1
- python - 从 Python 到 VB.NET 的代码转换:使用字节
- c# - 如何在 c# 代码中通过引用调用时从 c++ dll 更新数组值?
- c++ - 如何在不设置值的情况下通知 c++ 未来?
- google-cloud-platform - 如何在谷歌云存储权限中将访问限制为仅服务帐户用户
- javascript - React getDerivedStateFromProps 无法访问此
- java - 如何让信任锚在 Android API 级别 16-19 上正常工作