Plotting Any X-Y Graph With JavaScript
If I have any one-variable function, I can plot it out on web using JavaScriopt. The trick is to calculate all x-y pairs and use any open-sourced ploting JavaScript libray to draw it out.
So the key point is the JavaScript function to calculate all y when we have x.
Define Domain
Domain mean what x are. The basic way to get x is to use the for loop. For example, here is a domain of 1 - 10
var x = [];
for(let i = 1;i<=100;i++){
x.push(x);
};
Now we havre x, we need y. All we need to do is store calculated y value into an array.
var x = [];
var y = [];
var a = 5;
var b = 10;
for(let i = 1;i<=10;i++){
x.push(x);
y.push(a*i+b);
};
console.log(y)
//[15, 20, 25, 30, 35, 40, 45, 50, 55, 60]
Smaller Increments
The above example is with x addig 1 at a time, we can make a liitle adjustment so that x can incrase with a smaller increament, which could make our graph more continuous. In fact, if we want to find out if a
function converges, we need to make gaps between relatetivelt small.
var x = [];
var y = [];
var a = 5;
var b = 10;
for(let i = 1;i<=2;i=i+0.1){
x.push(x);
y.push(a*i+b);
};
Use of Array method: forRach()
If your x array is a set of given numbers, we can use the forEach loop to do the same thing.
var x = [3,6,8,9,11];
var y = [];
var a = 5;
var b = 10;
x.forEach(i=>{
y.push(a*i+b);
});
console.log(y)
//[25, 40, 50, 55, 65]
Plot it
Finally, we just need to use any free JS ploting library to plot it. Here I use the free Plotly.js to draw a linear function.
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="plot" style="width: 100%;"></div>
<script>
var xValues, yValue;
var a = 1;
var b = 1;
function draw(){
xValues = []; yValues = [];
for(i = -100;i<=100;i++){
xValues.push(i);
yValues.push(a*i + Number(b));
};
const data = [{
x: xValues,
y: yValues,
mode:"lines"
}];
const layout = {title: "y = " + a + "*x + " + b};
Plotly.newPlot("plot", data, layout);
};
draw();
</script>
Comments
Post a Comment