How to have the same scale in both x and y

老子叫甜甜 提交于 2019-12-24 17:21:18

问题


I have this graph : http://jsfiddle.net/thatOneGuy/Rt65L/94/

I can't seem to figure out how to get the same scale in both x and y. What I need is the same distance between the ticks on both but I need the x axis to be 600px long and y axis to be 300px high.

I have tried calling the same scale but obviously the x scale is too big for the y. Any ideas ?

<svg id='svgContainer' width="1000" height="700"> </svg>
var container = d3.select('#svgContainer') 
  .style('stroke', 'red')  

var width = 600, height = 300;

var xScale = d3.scale.linear()
  .range([0, width]);

var yScale = d3.scale.linear()
  .range([0, height]);

var xTicks = width/50;
var yTicks = height/50;
var xAxis = d3.svg.axis()
  .scale(xScale)
  .innerTickSize(-(height)) // vertical grid lines
  .outerTickSize(0)
  .orient("bottom")
  .ticks(xTicks);

var yAxis = d3.svg.axis()
  .scale(yScale)
  .innerTickSize(-(width)) // horizontal grid lines
  .outerTickSize(0)
  .orient("left")
  .ticks(yTicks);

container.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(50," + (height+20) + ")")
  .call(xAxis)

container.append("g")
  .attr("class", "y axis")
  .attr("transform", "translate(50,20)")
  .call(yAxis)

回答1:


If you don't set the domain, D3 will automatically set it as [0, 1]. So, I believe that, in your case, it's simply a matter of setting the domains:

var xScale = d3.scale.linear()
    .range([0, width])
    .domain([0,1]);

var yScale = d3.scale.linear()
    .range([height, 0])
    .domain([0,0.5]);

Here is the fiddle: http://jsfiddle.net/gerardofurtado/Rt65L/96/



来源:https://stackoverflow.com/questions/38703143/how-to-have-the-same-scale-in-both-x-and-y

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