我使用 Google Charts 使用许多不同的数据点绘制了折线图。
我想知道如何确定图表上任意 x 值处的 y 值,而不仅仅是数据点。
“我绘制的图表”
例如,如何找到 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/