使用d3.js将x轴移动到图表上的坐标(0,0)
您可以在第页看到我试图实现的一个示例 我用这个代码构造了负轴和正轴:使用d3.js将x轴移动到图表上的坐标(0,0),d3.js,D3.js,您可以在第页看到我试图实现的一个示例 我用这个代码构造了负轴和正轴: this.svg = d3.select(el).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + m
this.svg = d3.select(el).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
this.xScale = d3.scale.linear()
.range([0, width]);
this.yScale = d3.scale.linear()
.range([height, 0]);
const xAxis = d3.svg.axis()
.scale(this.xScale);
const yAxis = d3.svg.axis()
.orient('left')
.scale(this.yScale);
const data = this.getDataFromProps(this.props.expression);
this.xScale.domain(d3.extent(data, function (d) {return d.x;}));
this.yScale.domain(d3.extent(data, function (d) {return d.y;}));
this.svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
this.svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(' + width/2 + ',0)')
.call(yAxis);
唯一的问题是x轴朝向底部。如何将轴定位在svg上的(0,0)位置?只需更改此行:
this.svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0,' + (height/2) + ')')
.call(xAxis);
使转换为svg高度的一半 要使x轴与y轴的0标记对齐,请使用以下命令:-
this.svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0,' + (this.yScale(0)) + ')')
.call(xAxis);
为什么“平移”用于d3中的轴?为什么我们不能像在普通的非svg html元素上那样设置位置/边距/填充?您可以使用CSS来定位,但正确的方法是对svg元素使用转换。这仅在图形对称的情况下有效@下面的LIQvID使用yScale(0)有一个更通用的解决方案。