如何使用谷歌图表确定y坐标?

时间:2014-09-08 02:36:09

标签: javascript html google-visualization

我使用Google Charts使用许多不同的数据点绘制了折线图。

我想知道如何确定图表上任何x值的y值,而不仅仅是数据点。

"我绘制的图表" http://i.imgur.com/NbvAM3C.jpg

例如,如何在x = 1000处找到y坐标?

如果使用Google Charts无法做到这一点,哪个库最适合此任务?

1 个答案:

答案 0 :(得分:1)

这是jsfiddle:http://jsfiddle.net/mhmpn3wo/1/

Google Visualization不提供API来获取数据点之间的数据。但是,我们可以使用数据点的x坐标和y值来计算y值。(坐标是鼠标位置。) 例如,有两个点(10,100)和(20,200)。我们可以通过

获得x = 15的y值

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

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

我们需要像(x坐标,y值)这样的数据点对的数组。在Google LineChart中,数据点的坐标是$m.xZ对象的属性名称LineChart$m.xZ函数调用后设置LineChart.draw()

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)});
}

现在,lines数组包含数据点的所有x坐标和y值对。我们需要在图表上附加鼠标移动事件处理程序。

google.visualization.events.addListener(chart, 'onmousemove', mouseMoveHandler);
function mouseMoveHandler(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;
            }
        }
    }
}