Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

d3.js

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?

like image 292
dagda1 Avatar asked Jan 09 '16 08:01

dagda1


2 Answers

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);
like image 197
LIQvID Avatar answered Nov 16 '22 22:11

LIQvID


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.

like image 34
Cyril Cherian Avatar answered Nov 16 '22 22:11

Cyril Cherian