D3.js折线图坐标轴总偏移到角落怎么办?
在用D3.js画折线图时,坐标轴突然跑到svg左下角去了,明明之前代码没问题。我按照教程设置了margin对象,用scale()定义了范围,但y轴标签直接贴到y=0的位置,x轴完全看不见了。
尝试过调整attr("transform")的参数,把translate(0, ${height})改成translate(${margin.top}, ${margin.right})反而更糟。错误提示说NaN,发现是计算高度时漏掉了margin.bottom?
const margin = {top: 20, right: 30, bottom: 30, left: 40};
const width = 600 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;
// 错误的轴定位写法
svg.append("g")
.call(d3.axisBottom(x))
.attr("transform", <code>translate(${margin.left}, 0)</code>); // 这里应该定位到下方?
检查了数据绑定没问题,坐标轴的位置计算到底哪里出错了?
记得绘图区域用g包一层做整体位移才不会乱: