D3JS 图绘制在不正确的坐标处

d3js graph plotting at incorrect coordinates

本文关键字:坐标 不正确 绘制 D3JS      更新时间:2023-09-26

我试图绘制简单的D3JS图。我完成了绘制轴,甚至绘制了数据,但数据没有出现在预期的位置。

根据我下面的json数据

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

我试图在coordinates x axis 30 and y axis 10处画一个圆,但图表上的圆出现在其他地方。

这是 jsfiddle 演示

这是我的代码

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

如果你

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

在这里工作。

您的圆出现在像素 (30,10) 处,但这与轴标记的位置 30,10 不对应。使用比例设置点的位置。

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

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

看这个 jsFiddle

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

实际上它工作正常。 只是左上角是(0,0)而不是左下角(我怀疑,你必须假设)。

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