2017-04-06 46 views
1

我正在使用d3.js加载一些外部数据。我设法将这些数据呈现在我的阴谋的正确位置。使用拖放操作更新对象的位置。现在我想将这个位置转换回y轴的相应值,但我不知道如何做到这一点。将像素偏移量转换回值,反之亦然

Data.csv:

date,value 
2017-02-02,30.5 

数据加载:

d3.csv("data.csv", function(error, data) { 
    if (error) throw error; 

    // format the data 
    data.forEach(function(d) { 
     d.date = parseTime(d.date); 
     d.value = +d.value; 
    }); 


    dataPoints = data; 

}); 

秤对象

self.x = d3.scaleTime() 
    .domain([new Date(2017, 1, 1), new Date(2017, 1, 14)]) 
    .range([0, self.size.width]); 


self.y = d3.scaleLinear() 
    .domain([self.options.ymin, self.options.ymax]) 
    .range([self.size.height, 0]); 

更新位置:

svg.selectAll('circle') 
    .data(dataPoints) 
    .enter() 
    .append('circle') 
    .attr('r', 7) 
    .attr('cx', function (d) { 
     return self.x(d.date); 
    }) 
    .attr("cy", function (d) { 
     return self.y(d.value); 
    }) 
    .call(d3.drag().on('drag', function(d) { 
     d3.select(this).attr('cy', d.y = d3.event.y); 
    })); 

变焦功能

var transform = d3.event.transform; 

var xNewScale = transform.rescaleX(this.x); 
this.gX.call(this.xAxis.scale(xNewScale)); 

var yNewScale = transform.rescaleY(this.y); 
this.gY.call(this.yAxis.scale(yNewScale)); 

svg.selectAll('circle') 
    .attr('cx', function (d) { 
     return transform.applyX(self.x(d.date)); 
    }) 
    .attr('cy', function (d) { 
     return transform.applyY(self.y(d.value)); 
    }); 

解决了!

我改变了这一点:

对象的更新位置:

svg.selectAll('circle') 
    .data(dataPoints) 
    .enter() 
    .append('circle') 
    .attr('r', 7) 
    .attr('cx', function (d) { 
     return self.x(d.date); 
    }) 
    .attr("cy", function (d) { 
     return self.y(d.value); 
    }) 
    .call(d3.drag().on('drag', function(d) { 
     d3.select(this).attr('cy', d.y = d3.event.y); 
    })); 

这样:

svg.selectAll('circle') 
    .data(dataPoints) 
    .enter() 
    .append('circle') 
    .attr('r', 7) 
    .attr('cx', function (d) { 
     return self.x(d.date); 
    }) 
    .attr("cy", function (d) { 
     return self.y(d.value); 
    }) 
    .call(d3.drag().on('drag', function(d) { 
     d.value = self.y.invert(d3.event.y); 
     d3.select(this).attr('cy', self.y(d.value)); 
    })); 

回答

0

要获得在y轴的新位置的相应值,你必须使用invert

给定范围内的值,返回域中的相应值。反演是互动有益的,说来确定对应于鼠标的位置

所以数据值,例如:

var y = d3.scaleLinear() 
 
    .domain([0, 10]) 
 
    .range([0, 500]); 
 
    
 
console.log(y.invert(350)); 
 
console.log(y.invert(40)); 
 
console.log(y.invert(500));
<script src="https://d3js.org/d3.v4.min.js"></script>

+0

谢谢你,它像一个魅力。我更新了这个问题。 – Pascal

相关问题