Отображение сюжета matplotlib с помощью Flask - PullRequest
1 голос
/ 30 апреля 2019

Я хочу визуализировать график (SciView) в моем веб-проекте Flask.

Вот мой код:

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()

Я пытался запустить этот код в своем проекте Flask,но нет выхода.

1 Ответ

1 голос
/ 03 мая 2019

Возможное решение - сохранить рисунок с помощью plt.savefig и прикрепить его к элементу HTML <img>.

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()

Затем на /templates/plot.html

<img src={{url}} alt="Chart" height="auto" width="100%">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...