move x axis to coordinate (0,0) on the chart with d3.js

≯℡__Kan透↙ 提交于 2020-05-11 08:31:24

问题


You can see an example of what I am trying to achieve on this page.

I have negative and positive axis constructed with this code:

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);

The only problem is that the x-axis is oriented to the bottom. How can I have the axis positioned at (0, 0) on the svg?


回答1:


Just make this line change:

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

Make the translate to half of the height of svg.




回答2:


to make the x axis aligned to 0 mark of y-axis, use this :-

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


来源:https://stackoverflow.com/questions/34691285/move-x-axis-to-coordinate-0-0-on-the-chart-with-d3-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!