charts - Add a vertical line marker to Google Visualization's LineChart that moves when mouse move? -
is possible display vertical line marker showing current x-axis value on linechart, , moving when mouse moves ?
thanks in advance.
while difficult before, recent update api makes easier! need use mouseover event handler mouse coordinates , new chartlayoutinterface translate coordinates chart values. here's example code:
[edit - fixed cross-browser compatibility issue] *[edit - updated value of points near annotation line]*
function drawchart() { // create , populate data table. var data = new google.visualization.datatable(); data.addcolumn('number', 'x'); // add "annotation" role column domain column data.addcolumn({type: 'string', role: 'annotation'}); data.addcolumn('number', 'y'); // add 100 rows of pseudorandom data var y = 50; (var = 0; < 100; i++) { y += math.floor(math.random() * 5) * math.pow(-1, math.floor(math.random() * 2)); data.addrow([i, null, y]); } // add blank row end of datatable hold annotations data.addrow([null, null, null]); // index of row used annotations var annotationrowindex = data.getnumberofrows() - 1; var options = { annotation: { 1: { // set style of domain column annotations "line" style: 'line' } }, height: 400, width: 600 }; // create chart var chart = new google.visualization.linechart(document.getelementbyid('chart_div')); // create 'ready' event listener add mousemove event listener chart var runonce = google.visualization.events.addlistener(chart, 'ready', function () { google.visualization.events.removelistener(runonce); // create mousemove event listener in chart's container // use jquery, can use whatever works best $('#chart_div').mousemove(function (e) { var xpos = e.pagex - container.offsetleft; var ypos = e.pagey - container.offsettop; var cli = chart.getchartlayoutinterface(); var xbounds = cli.getboundingbox('haxis#0#gridline'); var ybounds = cli.getboundingbox('vaxis#0#gridline'); // mouse inside chart area? if ( (xpos >= xbounds.left || xpos <= xbounds.left + xbounds.width) && (ypos >= ybounds.top || ypos <= ybounds.top + ybounds.height) ) { // if so, draw vertical line here // x-axis value @ these coordinates var xval = cli.gethaxisvalue(xpos); // set x-axis value of annotation data.setvalue(annotationrowindex, 0, xval); // set value display on line, value want data.setvalue(annotationrowindex, 1, xval.tofixed(2)); // data value (if any) @ line // truncating xval 1 decimal place, // since unlikely find annotation aligns precisely data var rows = data.getfilteredrows([{column: 0, value: parsefloat(xval.tofixed(1))}]); if (rows.length) { var value = data.getvalue(rows[0], 2); // value } // draw chart new annotation chart.draw(data, options); } }); }); // draw chart chart.draw(data, options); }
see working here: http://jsfiddle.net/asgallant/tvcv9/12
Comments
Post a Comment