做数据统计工作的同学,应该经常会需要把一些公式,拟合函数绘制出来,去找到一个数学公式的视觉信息。
比如下图是公式
y = Math.sin(5 * x) / x
的可视化图。
y = Math.sin(5 * x) / x 的可视化
所以想参考这个,可视化一下我们熟知的函数,看看他们的可视化表现到底是什么?要做到这个,有几个事情:
根据公式生成数据
需要定义一个函数,传入公式的表达字符串,然后就可以根据这个公式传入 x 数据,返回 y 数据,然后通过一个生成器,产生数组数据。
因为要执行一个字符串,需要使用
eval
或者
newFunction
函数。
function getY(formula, x) {
return eval(formula);
}
function generateX(start, end, count) {
return [
...new Array(count).fill(0).map((_, i) => start + (end - start) / count * i)
];
}
function generateData(formula, start, end, count) {
const xArr = generateX(start, end, count)
return xArr.map(x => {
return [x, getY(formula, x)];
})
}
绘制
有了 x y 的数据数组之后,绘制对于 AntV 来说就非常简单的,直接使用 G2 的曲线图就可以了。
const chart = new Chart({
container: 'container',
autoFit: true,
});
chart.data(DATA);
chart
.line()
.encode("x", "x")
.encode("y", "y")
.encode("shape", "smooth")
.style("stroke", "#" + Math.floor(Math.random() * 16777215).toString(16))
.style("lineWidth", 2)
.scale("x", { nice: true })
.scale("y", { nice: true });
chart.render();
看看效果 y = Math.sin(5 * x) / x 的效果。
y = Math.sin(5 * x) / x 的可视化效果
再多加几个公式,如下表:
y =
x
y = 2*x
+
1
y = x*x - 1
y = x * x * x
y = Math.sin(x)
y = Math.sin(x * x * x)
y = Math.sin(Math.tan(x))
y = 1/x
y = x + 1/x
y = Math.sin(5 * x) / x
y = Math.sqrt(x*x, 3) + 0.99 * Math.sqrt((3.3 - x*x), 2) * Math.sin(9.9 * Math.PI * x)
还希望可视化什么公式呢,可以留言,也可以自己 cp 代码试试吧!
最后
文章中的一些函数,参考于文章《使用 canvas 画布可以做的一些有意思的事情》
https://juejin.cn/post/7287018116969971751#heading-16
,绘制上改成使用 G2,因为带有 scale 逻辑,所以 x y 轴显示范围可以自动显示。
最后,可以到这里去体验一下
Visualize some mathematical functions!:
https://observablehq.com/d/13798927932ac5ae
往期回顾