使用d3.js将x轴移动到图表上的坐标(0,0)

vdzxcuhz  于 2023-06-23  发布在  其他
关注(0)|答案(2)|浏览(158)

你可以在this页面上看到一个我试图实现的示例。
我用下面的代码构造了负轴和正轴:

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)处?

yruzcnhs

yruzcnhs1#

要使x轴与y轴的0标记对齐,请使用以下命令:-

this.svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0,' + (this.yScale(0)) + ')')
.call(xAxis);
qoefvg9y

qoefvg9y2#

只需更改这一行:

this.svg.append('g')
  .attr('class', 'axis')
  .attr('transform', 'translate(0,' + (height/2) + ')')
  .call(xAxis);

将其平移到svg高度的一半。

相关问题