Skip to content Skip to sidebar Skip to footer

How To Determine The Y Coordinate Using Google Charts?

I have drawn a line graph using Google Charts using a number of different data points. I want to know how I can determine the y-value at any x-value on the graph and not just the

Solution 1:

This is jsfiddle :http://jsfiddle.net/mhmpn3wo/1/

Google Visualization does not provide API to get data between data points. However, we can calculate y-values using x-coordinates and y-values of data points.(Coordinate is mouse position.) For example, there are two points (10, 100) and (20, 200). We can get y-value at x = 15 by

f(15) = (200 - 100) / (20 - 10) * (15 - 10) + 100 = 150

f(x) = (y2 - y1)/(x2 - x1) * (x1 - x) + y1 = y

We need array of data points pairs like (x-coordinate, y-value). In Google LineChart, coordinates of data points are property name $m.xZ of LineChart object.($m.xZ is set after LineChart.draw() function call)

var data = google.visualization.arrayToDataTable([
    ['Year', 'Sales', 'Expenses'],
    ['2004', 1000, 400],
    ['2005', 1170, 460],
    ['2006', 660, 1120],
    ['2007', 1030, 540]
]);

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {});

var lines = [];

for (var propertyName in chart.$m.mZ) {
    var id = propertyName.split('#');
    var coordinate = chart.$m.mZ[propertyName].center;
    if (typeof lines[id[1]] === "undefined") {
        lines[id[1]] = [];
    }
    lines[id[1]].push({x: coordinate.x, value: parseFloat(data.Ad[parseInt(id[2])][parseInt(id[1]) + 1].Pe)});
}

Now, lines array contains all pairs of x-coordinate and y-value of data points. We need to attach mouse move event handler on the chart.

google.visualization.events.addListener(chart, 'onmousemove', mouseMoveHandler);
functionmouseMoveHandler(e) {
    var target = e.targetID.split("#");
    if (target[0] === "line") {
        var currentLine = lines[parseInt(target[1])];
        var count = currentLine.length;
        for (var i = 0; i < count; i++) {
            if (currentLine[i].x >= e.x) {
                var slope = (currentLine[i].value - currentLine[i - 1].value) / (currentLine[i].x - currentLine[i - 1].x);
                var value = ((e.x - currentLine[i - 1].x) * slope + currentLine[i - 1].value).toFixed(2);
                $("#tooltip").css('left', e.x + "px").css('top', (e.y - 20) + "px").html(value).show();

                break;
            }
        }
    }
}

Post a Comment for "How To Determine The Y Coordinate Using Google Charts?"