2

I have already read the following Call Python function from JavaScript code

interpol.py

import numpy as np
from math import sqrt
import matplotlib.pyplot as plt

def interpol(x0, x, y):
    x = np.asfarray(x)
    y = np.asfarray(y)
    ....
    return f0

if __name__ == '__main__':

    x = [-5,-4.19,-3.54,-3.31,-2.56,-2.31,-1.66,-0.96,-0.22,0.62,1.21]
    y = [0.01,0.01,0.03,0.04,0.07,0.09,0.16,0.28,0.45,0.65,0.77]
    plt.scatter(x, y)
    x_new = np.linspace(-6, 2)
    plt.plot(x_new, interpol(x_new, x, y)) #output the figure

    plt.show()

This python code output a figure.

I would like get x and y arrays from html input and give them to the python code (In this example I use x and y in the python, but I would like to get those from html input), and output the python figure into the webpage.

I know that I have to use server and I would like to use jQuery.ajax().

2 Answers 2

1

Adding to previous answer, you can save the figure as an image to a ByteIO stream. Then serve it as an image. That avoids having to use temporary files. The other option is to use the Plotly library that provides excellent interactivity.

Sign up to request clarification or add additional context in comments.

Comments

0

Disclaimer: This is a very broad question for which I can only give a very high-level answer.

You have different strategies to

"add matplotlib figures into webpage"

  1. Save the matplotlib graphs into svg/png format and include them in the rendered webpage, plt.savefig("test.svg", format="svg").
    • Pro(s): Easy, no need for advanced JS at your client code (This can be done without using javascript at all actually)
    • Con(s): The client UI will not be interactive.
  2. Convert your graphs into JSON objects via for example mpld3 and render them in your client code with D3.js.
    • Pro(s): This will allow you to have interactive graphs at client side.
    • Con(s): A little bit more complex than the first option.
  3. Bonus: For more advanced graphs you can directly use altair at python level to generate your graphs. https://altair-viz.github.io/ and render them at your client level via vega-embed. For more details: https://altair-viz.github.io/user_guide/display_frontends.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.