1

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 }}">

1 Answer 1

2

The reason for this is because it is updating on the only available canvas or window. In order to display the two images separately, you need to create two separate windows so as to retain both of the plots.

To do this include the line

plt.figure()

..before

plt.plot() 

In both rendergraph1() and rendergraph() methods.

This should take care of the issue. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.