Is there any way to plot a line based on an equation? e.g.: y = 2x + 5?
I guess that one workaround would be to create a CSV file with the respective x and y values and then plotting from it but I was wondering if there is any other way?
Something like this should work:
{
let f = (x) => 2 * x + 5;
let [a, b] = [-5, 5];
return Plot.plot({
marks: [
Plot.line([
[a, f(a)],
[b, f(b)]
]),
Plot.axisX({ y: 0 }),
Plot.axisY({ x: 0 }),
Plot.ruleX([0]),
Plot.ruleY([0])
]
});
}
If you’d like the slope of the line to “look” like it’s two, then you need to set the width
and height
of the plot as well to match the domain and range of your graph.
1 Like
For a more general solution for plotting any function, see
https://observablehq.com/d/a35b4c47e65337bc
1 Like
Thank you! This works so well for me although I was hopping for something like:
Plot.plot({
marks: [
Plot.function(function, {xmin: -5, xmax: 5, int: 0.05})
]
})
Where the equation is defined from:
f = (x) => 1 + x + 2 * x*x
This is basically a new mark
only for plotting functions.
Plotting a line and plotting a more general function are two very different things. If I had known that was your objective, I would probably have pointed you here:
I really should update that in light of some improvements, though - the axis mark, in particular.
1 Like