0
我有兩個鏈接,每個映射到不同的matplotlib可視化文件,例如:localhost:5000/line_chart和localhost:5000/bar_chart。在燒瓶中映射到不同matplotlib圖形的多路徑應用程序
當我啓動服務器,並點擊一條路徑(其中任何一個),我看到了我的期望。
本地主機:5000/bar_chart
當我回去查看其他環節,兩個圖形突破。
本地主機:5000/line_chart
本地主機:5000/bar_chart
我可以通過關閉服務器,然後運行 「run.py」 重現此每次腳本再次。似乎是與內存緩衝區的覆蓋衝突。有沒有人有過這個問題?
應用程序/ views.py
import matplotlib
matplotlib.use('Agg') # this allows PNG plotting
import matplotlib.pyplot as plt
import base64
from flask import render_template
from app import app
from io import BytesIO
@app.route('/')
@app.route('/index')
def index():
res = ''
navigation = [['Line Chart','line_chart'],['Bar Chart','bar_chart']]
res = res + '<h1>Matplotlib Chart Examples</h1>'
res = res + '<ul>'
for item in navigation:
name = item[0]
link = item[1]
res = res + '<li><a href="' + link + '">'+ name +'</a></li>'
res = res +'</ul>'
return res
@app.route('/bar_chart')
def bar_chart():
movies = ["Annie Hall", "Ben-Hur", "Casablanca", "Gandhi", "West Side Story"]
num_oscars = [5, 11, 3, 8, 10]
# bars are by default width 0.8, so we'll add 0.1 to the left coordinates
# so that each bar is centered
xs = [i + 0.1 for i, _ in enumerate(movies)]
# plot bars with left x-coordinates [xs], heights [num_oscars]
plt.bar(xs, num_oscars)
plt.ylabel("# of Academy Awards")
plt.title("My Favorite Movies")
# label x-axis with movie names at bar centers
plt.xticks([i + 0.5 for i, _ in enumerate(movies)], movies)
return compute(plt)
@app.route('/line_chart')
def line_chart():
years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]
# create a line chart, years on x-axis, gdp on y-axis
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')
# add a title
plt.title("Nominal GDP")
# add a label to the y-axis
plt.ylabel("Billions of $")
return compute(plt)
def compute(plt):
# run plt.plot, plt.title, etc.
figfile = BytesIO()
plt.savefig(figfile, format='png')
figfile.seek(0) # rewind to beginning of file
#figfile.getvalue() extracts string (stream of bytes)
figdata_png = base64.b64encode(figfile.getvalue())
return render_template('index.html',
title='matplotlib chart',
results=figdata_png)
謝謝您的時間。
奏效。哇..非常感謝你。在過去的兩週裏,這一直困擾着我。 –