I have to display 2 matplotlib graphs in my flask template. I am getting desired output but, as I am new to matplotlib, I can't figure out why after refresh the first bar graph changes to the second plot. Here are three functions that are doing the job.
import matplotlib.pyplot as plt
import base64
import StringIO
@app.route('/FirmIn/admin/')
def admin():
plot_url=rendergraph1()
plot_url2=rendergraph2()
return render_template('admin.html', plot_url=plot_url, plot_url2=plot_url2)
def rendergraph1():
cursor.execute("SELECT category,count(*) from project_info group by category")
dataall=cursor.fetchall()
img = StringIO.StringIO()
category,index,count =[],[],[]
i=0
for data in dataall:
category.append(data[0])
index.append(i)
count.append(data[1])
i=i+1
print index, count
plt.bar(index, count, color = 'r')
plt.xticks(index, category, rotation=25)
plt.yticks(range(min(count), max(count)+1))
plt.rcParams['xtick.major.pad']='5'
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()
return plot_url
def rendergraph2():
cursor.execute("SELECT category,sum(project_cost) from project_info group by category")
img = StringIO.StringIO()
dataall=cursor.fetchall()
category,index,cost =[],[],[]
i=0
for data in dataall:
category.append(data[0])
index.append(i)
cost.append(data[1])
i=i+1
plt.plot(index,cost)
plt.xticks(index, category, rotation=25)
plt.savefig(img, format='png')
img.seek(0)
plot_url2 = base64.b64encode(img.getvalue()).decode()
return plot_url2
And inside template I am displaying using:
<img style="height:400px" src="data:image/png;base64, {{ plot_url }}">
<img style="height:400px" src="data:image/png;base64, {{ plot_url2 }}">