2017-04-06 78 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

相關問題