Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying matplotlib plot using Flask

I want to visualize the plot (SciView) in my Flask web project.

Here is my code:

import matplotlib.pyplot as plt 
# x-coordinates of left sides of bars 
left = [1, 2, 3, 4, 5] 
# heights of bars 
height = [10, 24, 36, 40, 5] 
# labels for bars 
tick_label = ['one', 'two', 'three', 'four', 'five'] 
# plotting a bar chart 
plt.bar(left, height, tick_label=tick_label, width=0.8, color=['red', 'green']) 
# naming the y-axis 
plt.xlabel('y - axis') 
# naming the x-axis 
plt.xlabel('x - axis') 
# plot title 
plt.title('My bar chart!') 
# function to show the plot 
plt.show()

I've tried running this code in my Flask project, but there is no output.

like image 418
Lamine Sirine Avatar asked Apr 30 '19 15:04

Lamine Sirine


People also ask

Can matplotlib plot in terminal?

The best use of Matplotlib differs depending on how you are using it; roughly, the three applicable contexts are using Matplotlib in a script, in an IPython terminal, or in an IPython notebook.


1 Answers

A possible solution is to save the figure with plt.savefig and attach it to an HTML <img> tag.

from flask import Flask, render_template
import matplotlib.pyplot as plt

app = Flask(__name__)

@app.route('/plot')
def plot():
    left = [1, 2, 3, 4, 5]
    # heights of bars
    height = [10, 24, 36, 40, 5]
    # labels for bars
    tick_label = ['one', 'two', 'three', 'four', 'five']
    # plotting a bar chart
    plt.bar(left, height, tick_label=tick_label, width=0.8, color=['red', 'green'])

    # naming the y-axis
    plt.ylabel('y - axis')
    # naming the x-axis
    plt.xlabel('x - axis')
    # plot title
    plt.title('My bar chart!')

    plt.savefig('static/images/plot.png')

    return render_template('plot.html', url='/static/images/plot.png')

if __name__ == '__main__':
   app.run()

Then on templates/plot.html

<img src={{url}} alt="Chart" height="auto" width="100%">
like image 86
Gabe H. Avatar answered Oct 05 '22 23:10

Gabe H.