我有一个 ScatterChart,我需要在其中绘制一条(函数 y=x 的)对 Angular 线,作为视觉辅助。可能吗 ?如果是这样,我该怎么做?
最佳答案
另一种解决方案是您可以使用 Scatter
多系列图表,并设置lineWidth = 1
和 pointSize = 0
对于 Line
图表!
请参见以下示例:
function main() {
const xMin = -2 * Math.PI;
const xMax = 2 * Math.PI;
const f1 = x => Math.cos(x) + Math.random();
const f2 = x => Math.cos(x);
const x = linspace(xMin, xMax, 20);
const y1 = x.map(f1);
const y2 = x.map(f2);
scatterLineChart(document.getElementById('scatter-line-chart'), x, [y1, y2], 'Scatter: Cos(x) + Noise, Line: Cos(x)', 'x', ['Cos(x) + Noise', 'Cos(x)']);
}
function linspace(a, b, n = 100) {
const data = new Array(n);
const d = (b - a) / (n - 1);
data[0] = a;
data[n - 1] = b;
n = n - 1;
for (let i = 1; i < n; i++) {
data[i] = data[i - 1] + d;
}
return data;
}
function createSeriesDataTable(x, ys, xLabel, yLabels) {
// data
const data = new google.visualization.DataTable();
// - columns
data.addColumn('number', xLabel);
yLabels.forEach(yLabel => {
data.addColumn('number', yLabel);
});
// - rows
const n = x.length;
const m = ys.length;
const rows = Array(n);
for (let i = 0; i < n; i++) {
rows[i] = Array(1 + m);
rows[i][0] = x[i];
for (let j = 0; j < m; j++) {
rows[i][j + 1] = ys[j][i];
}
}
data.addRows(rows);
// return
return data;
}
function scatterLineChart(parentElement, x, ys, title, xLabel, yLabels) {
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
const data = createSeriesDataTable(x, ys, xLabel, yLabels);
const options = {
title: title,
series: {
1: {
lineWidth: 3,
pointSize: 0,
curveType: 'function'
},
},
legend: 'none'
};
const chart = new google.visualization.ScatterChart(parentElement);
chart.draw(data, options);
}
}
main();
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="scatter-line-chart"></div>
关于javascript - 在 Google Charts ScatterChart 上画一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42891409/