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

标签 javascript html google-visualization

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

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

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

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

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

最佳答案

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

Google 可视化不提供 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中,数据点的坐标是LineChart对象的属性名称$m.xZ。($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;
            }
        }
    }
}

关于javascript - 如何使用谷歌图表确定y坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25716749/

相关文章:

javascript - Google Charts 多个 vAxis textStyle 和 textPosition 的错误

javascript - Google Charts 条形图最后一个值标签截止

javascript - 如何使用Jquery获取点击的div内输入标签的值?

javascript - 如何在悬停时显示图像标题文本?

javascript - 如果我按F5,输入值不会重置1,但如果我按ctrl+f5或在url搜索栏中按Enter键,输入值会重置1?为什么?

javascript - 在同一 Canvas 中顺时针旋转一个轮子,逆时针旋转另一个轮子

html - 使用 CSS 居中一些内容

javascript - 如何更改谷歌图表工具提示的弹出位置

javascript - 为 Next.js 的服务器文件设置自定义目录

javascript - jQuery 每个函数在 ajax 调用后不起作用