Plot function on top of existing `Plot`

Hi,

I have described my question in a notebook here: problem description

Thanks!

1 Like

Judging from your notebook, youâ€™re asking how to generate an application that looks something like so:

where the scatter plot comes from some data file and the linear fit comes from the text box, rather than from a computation based on the data.

I think that part of the reason that youâ€™re having a challenge is simply that many of the notebooks youâ€™re referring to are several years old now and the tools they use have been improved or superseded. For example,

• Thereâ€™s no need to `import` the `Text` input anymore. `Inputs.text` is now built in.
• The use of `build_samples` seems like overkill, since youâ€™re just plotting a line, which is determined by just two points. If youâ€™re doing logistic or polynomial regression, then I suppose `build_samples` might make sense.
• Most importantly - Mike Bostockâ€™s `funplot` is, well, pretty fun, but largely superseded by `Plot`. In fact, if your whole point is to lay down the plot of a function on top of a `Plot`, it makes sense to simply incorporate another mark.

Using some newer and simple tools, Iâ€™d do something like so:

First, define `f` using an `Inputs.text`:

``````viewof f = Inputs.text({ submit: true, label: tex`f(x):`, value: "50x - 5780" })
``````

Assuming youâ€™ve imported `math.js`, you can parse that into a computable function in a separate cell, like so:

``````ff = {
let ff = math.compile(f);
return (x) => ff.evaluate({ x: x });
}
``````

You can now use that `ff` function to generate a line mark doing something like so:

``````Plot.line(
[
[170, ff(170)],
[235, ff(235)]
],
{ strokeWidth: 3 }
)
``````

You can see all this in action in the notebook embedded above.

2 Likes

Thank you!

This is so cool! It allows for plotting any line according to any function and it doesnâ€™t have to be hardcoded. You can include any function in the text input

Here I used `build_samples` so any function is plotted (not just linear functions):

1 Like

Also note that, when using the embed feature, itâ€™s generally not necessary to embed dependencies. That is, if you wish to display two cells, say `f2` and `plot2`, you need only embed those and not, for example a dependency like `ff2`.