I would like to plot an image without having to save it in a static folder.
I've got an example posted here by user Messa working just fine:
import io
import random
from flask import Response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
@app.route('/plot.png')
def plot_png():
fig = create_figure()
output = io.BytesIO()
FigureCanvas(fig).print_png(output)
return Response(output.getvalue(), mimetype='image/png')
def create_figure():
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
xs = range(100)
ys = [random.randint(1, 50) for x in xs]
axis.plot(xs, ys)
return fig
Then in the HTML file:
<img src="/plot.png" alt="my plot">
The result is perfect. I get the image on the fly.
Now I would like to use some parameters like this:
@app.route('/<x_values_source>/<y_values_source>/plot.png')
def plot_png(x_values_source, y_values_source):
fig = create_figure(x_values_source, y_values_source)
output = io.BytesIO()
FigureCanvas(fig).print_png(output)
return Response(output.getvalue(), mimetype='image/png')
def create_figure(x_values_source, y_values_source):
x_values = function_that_returns_x_values_set(x_values_source)
y_values = function_that_returns_y_values_set(y_values_source)
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
axis.plot(x_values, y_values)
return fig
But of course It doesn't work. I'm quite new to Python and I'm still learing a lot of things.
Thanks!