2013-10-04 80 views
0

我试图绘制简单的d3js图形。我通过绘制坐标轴并绘制了数据,但数据并未出现在预期的位置。d3js图形坐标不正确

按我的JSON数据低于

var d1 = [{ 
     value1: "30", 
     value2: "10" 
    }]; 

我试图在coordinates x axis 30 and y axis 10绘制一个圆,但图上的圆圈出现一些别的地方。

这里是的jsfiddle demo

这里是我的代码

var d1 = [{ 
      value1: "30", 
      value2: "10" 
     }]; 



function Update(){ 
    var circles = vis.selectAll("circle").data(d1) 
    circles 
     .enter() 
      .insert("svg:circle") 
       .attr("cx", function (d) { return d.value1; }) 
       .attr("cy", function (d) { return d.value2; }) 
       .style("fill", "red") 
    circles 
     .transition().duration(1000) 
      .attr("cx", function (d) { return d.value1; }) 
      .attr("cy", function (d) { return d.value2; }) 
      .attr("r", function (d) { return 5; }) 

    circles.exit() 
     .transition().duration(1000) 
      .attr("r", 0) 
       .remove(); 


} 



/*************************************************/ 


/*******************Real Stuff starts here*******************/ 

var vis = d3.select("#visualisation"), 
    WIDTH = 600, 
    HEIGHT = 400, 
    MARGINS = { 
    top: 20, 
    right: 20, 
    bottom: 20, 
    left: 50 
    }, 
    xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([0,100]), 
    yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0,300]), 


    xAxis = d3.svg.axis() // generate an axis 
     .scale(xRange) // set the range of the axis 
     .tickSize(5) // height of the ticks 
     .tickSubdivide(true), // display ticks between text labels 
    yAxis = d3.svg.axis() // generate an axis 
     .scale(yRange) // set the range of the axis 
     .tickSize(5) // width of the ticks 
     .orient("left") // have the text labels on the left hand side 
     .tickSubdivide(true); // display ticks between text labels 

function init() { 
    vis.append("svg:g") // add a container for the axis 
    .attr("class", "x axis") // add some classes so we can style it 
    .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")") // move it into position 
    .call(xAxis); // finally, add the axis to the visualisation 

    vis.append("svg:g") 
    .attr("class", "y axis") 
    .attr("transform", "translate(" + (MARGINS.left) + ",0)") 
    .call(yAxis); 
} 
init(); 





$('#btn').click(function(){ 
    Update(); 
}); 

回答

1

它的工作原理,如果你

  • 定义数字作为数字而不是字符串(即value1: 30而不是value1: "30")和
  • 使用您定义的尺度(即return xRange(d.value1)而不是return d.value1)。

工作jsfiddle here

1

你的圆圈出现在像素(30,10),但这不符合的地方30,10作为标记由你的轴。使用你的磅秤来设置点的位置。

  .attr("cx", function (d) { return xRange(d.value1); }) 
      .attr("cy", function (d) { return yRange(d.value2); }) 
0

您需要将xScaleyScale应用于坐标以将它们转换为绘图空间。

this jsFiddle

.attr("cx", function (d) { return xRange(d.value1); }) 
.attr("cy", function (d) { return yRange(d.value2); }) 
0

其实这是工作的罚款。只是左上角是(0,0)而不是左下角(因为我怀疑你必须假设)。

将x,y都设为0.圆圈将出现在左上角。