0

This Method receives type of Graph is required, the file to work and the axes to graph

@app.route('/graficar',methods=['POST'])
def graficar():
    if request.method == 'POST':
         
        tipo=request.form['tipo']
        nombre=request.form['nombre']
        sep=request.form['sep']
        columnaX=request.form['columnaX']        
        columnaY=request.form['columnaY']
        ruta=request.form['fil']
        df =pd.read_csv(ruta, sep=sep )
        df=df.head(10)
        print(df.head(5))
        if tipo=='1':
            print('Lineal')
            plt.plot(df[columnaX],df[columnaY])
            plt.xticks(df[columnaX], rotation=75)
            plt.xlabel(columnaX)
            plt.ylabel(columnaY)
            plt.title(nombre)
            plt.show()
            plt.savefig('img/Grafica.png' )
            return render_template("Grafica.html")

HTML,I just send to call the image but it does not show me anything
enter image description here enter image description here

<div class="col-12">
      <h3 class="text-center display-2">Gráfica</h3>
      <div class="container ">
           <img class="img-fluid" src="img/Grafica.png" alt="Chania" />
      </div>
 </div>


  
MarcoE
  • 3
  • 2
  • 1
    Please, add Folders Map of your environment, the relation between the default folder of your code and that you store the image in, usually there is a `static` folder in which you can store your data to be published, thus the path used in programming is not the same as in HTML files. – Nour-Allah Hussein Jan 04 '21 at 13:24

1 Answers1

0

My suggestion would be to not save the file somewhere, but create the image on the fly. Create an endpoint that will serve the rendered image, and an endpoint that will render your page template. Separating these will make everything faster, easier to debug and more readable.

Have a look at this answer to get an idea of how to return an image from a Flask endpoint. Python: How to show matplotlib in flask

As a quick example of how it would work:

main.py:

import io
import random

from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from flask import Flask, Response, render_template, request

# Create the app
app = Flask(__name__)


def create_figure(title: str = "", **kwargs) -> Figure:

    # Create a plot here...
    figure = Figure()
    axis = figure.add_subplot(title=title)
    xs = range(100)
    ys = [random.randint(1, 50) for _ in xs]
    axis.plot(xs, ys)
    return figure


@app.route("/img/Grafica.png")
def get_image():

    # Get the input arguments (e.g. /img/Grafica.png?title=test)
    # You can also use request.form here
    args = dict(request.args)

    # Create the figure or whatever you need to plot
    figure = create_figure(**args)

    # Create a buffer to hold the PNG
    buffer = io.BytesIO()

    # Write the figure as PNG to the buffer
    FigureCanvas(figure).print_png(buffer)

    # Return the binary contents of the buffer, set the mimetype to indicate to the browser that we've send an image
    return Response(buffer.getvalue(), mimetype="image/png")


@app.route("/graficar")
def get_graficar():
    return render_template("Grafica.html")


if __name__ == "__main__":
    app.run(debug=True)

templates/Grafica.html:

<!doctype html>

<section class="content">
  <h1>Graficar</h1>
  <img src="/img/Grafica.png?title=My title" />
</section>

Output

Gijs Wobben
  • 1,974
  • 1
  • 10
  • 13