2017-10-09 47 views
1

我必须在烧瓶模板中显示2个matplotlib图。我正在得到所需的输出,但是,因为我是matplotlib的新手,我无法弄清楚为什么刷新后第一个棒图更改为第二个图。这里有三个功能正在完成这项工作。烧瓶模板matplotlib图刷新后错误

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 

而且里面的模板,我使用显示:

<img style="height:400px" src="data:image/png;base64, {{ plot_url }}"> 
<img style="height:400px" src="data:image/png;base64, {{ plot_url2 }}"> 

回答

2

这样做的原因是因为它是唯一可用的画布或窗口上的更新。为了分别显示两个图像,您需要创建两个单独的窗口以保留两个图。

要做到这一点包括行

plt.figure() 

..before

plt.plot() 

在这两个rendergraph1()rendergraph()方法。

这应该照顾到这个问题。 :)