javascript - D3.js get nearest X & Y coordinates for Area Chart -
hi have area chart several x (year) & y (price) values. i've found there easy way x, y coodinates value chart when user clicks on 1 of point on line clicking outside line i.e. svg/chart-body area can provide x, y coordinates of planes rather 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 there way nearest data coordinates when clicked on svg? e.g svg [605.5, 394.5] (something nearest [x, y] using)
{x: fri feb 01 1980 00:00:00 gmt+0000 (gmt standard time), y: 666}
or other way translate svg x, y data x, y?
original data in 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 = bisectdate(data, mousedate); // returns index current data item var d0 = data[i - 1] var d1 = data[i]; // work out date value closest mouse var d = mousedate - d0[0] > d1[0] - mousedate ? d1 : d0; var x = xscale(d[0]); var y = yscale(d[1]);
Comments
Post a Comment