Hi I have an area chart with several X (year) & Y (price) values. As I've found there is easy way to get X, Y coodinates value for chart when user clicks on one of the point on line however clicking outside line i.e. SVG/Chart-Body area can provide only X, Y which are coordinates of planes rather than data.
Point on Chart:
circles = c.svg().selectAll 'circle.dot'
circles.on 'click', (d) ->
console.log 'POINT', 'Datum:', d
O/P:
POINT Datum:
{x: Fri Feb 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 666}
Point outside chart:
svg.on 'click', () ->
console.log 'SVG', d3.mouse(@)
O/P:
SVG [605.5, 394.5]
Now is there any way I could get nearest data coordinates when clicked on SVG? e.g SVG [605.5, 394.5] would be (something like nearest [X, Y] using)
{x: Fri Feb 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 666}
or some other way to translate SVG X, Y into Data X, Y?
Original data is in the form of,
[
{x: Fri Jan 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 666},
{x: Fri Feb 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 668},
{x: Fri Mar 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 700},
{x: Fri Apr 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 750},
.
.
.
{x: Fri Dec 01 2010 00:00:00 GMT+0000 (GMT Standard Time), y: 2000},
.
.
.
]
http://bl.ocks.org/mikehadlow/93b471e569e31af07cd3
Using d3.bisector,
var mouse = d3.mouse(this);
var mouseDate = xScale.invert(mouse[0]);
var bisectDate = d3.bisector(function(d) { return d.x; }).left;
var i = bisectDate(data, mouseDate); // returns the index to the current data item
var d0 = data[i - 1]
var d1 = data[i];
// work out which date value is closest to the mouse
var d = mouseDate - d0[0] > d1[0] - mouseDate ? d1 : d0;
var x = xScale(d[0]);
var y = yScale(d[1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With