我创建了Django视图“graph”,目的是显示从matplotlib.pyplot模块。我编写了我的函数plot\u bubbles(返回amatplotlib.figure.figure对象)在脚本数据中_分析.py导入到视图.py脚本。在
Tkinter只能在主线程上运行,我的网页在我第一次请求时按预期工作,但在刷新或再次请求时它不显示图像。我的理解是,当视图再次被请求时,Django在一个新线程上操作代码。在from django.http import HttpResponse
from . import data_analysis
import Queue
import threading
q = Queue.Queue()
def graph(request):
parties = ["Conservative Party", "Labour Party", "Green Party", "UKIP"]
def from_other_thread(graph_function):
q.put(graph_function)
def main_thread_execute():
callback = q.get()
fig = callback
return fig
def grapher(arguments, area_variable):
data_analysis.plt.close('all')
from_other_thread(data_analysis.plot_bubbles(arguments, area_variable))
t = threading.Thread(target = grapher, args=(parties, data_analysis.all_data['2015 Pay']))
t.start()
t.join()
fig = main_thread_execute()
response = HttpResponse(content_type='image/png')
fig.savefig(response, format='png')
return response
其目的是在主线程中运行函数,以便Tkinter可以实际工作并创建图像我希望每次请求url时都创建图像,因为我将允许用户通过表单选择他想要可视化的变量,并将它们作为plot_bubbles函数的参数传递。在
我是django的初学者,从未在代码中使用过多线程,感谢您阅读本文。如有任何关于您的解决方案的解释,我们将不胜感激。在
编辑
不一定需要穿线。问题源于我的数据分析脚本生成绘图的方式。尤其是方法调用的代码matplotlib.pyplot.subplothttp://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots生成一个带有4个轴对象的图形
^{pr2}$
这似乎导致Tkinter无法在主循环上运行,我还没有完全理解原因。这就是代码现在的样子#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from pandas import Series, DataFrame
from pylab import figure, axes, plot, title, subplots
import statsmodels.api as sm
from sqlalchemy import create_engine
from matplotlib.backends.backend_agg import FigureCanvasAgg
import matplotlib
# Load data from database into dataframe
engine = create_engine("postgresql://user_name:password@localhost:5432/brexit")
all_data = pd.read_sql('''SELECT * FROM records;''', engine, index_col='Borough')
# Bubble Plot function creation
colors = np.random.rand(len(all_data.index))
area = []
def plot_bubbles(arguments, area_variable, space=0):
ah = iter(arguments)
eh = iter(arguments)
ih = iter(arguments)
kh = iter(arguments)
th = iter(arguments)
zh = iter(arguments)
mh = iter(arguments)
fig = figure(figsize=(30, 25))
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
collection = [ax1, ax2, ax3, ax4]
for x in area_variable:
#want the bubbles to have an average area of 40, add a factor to increase the variability in size
factor = ((x-area_variable.mean())**2/400)
area.append(factor*x*(40/area_variable.mean()))
for ax in collection:
orient = all_data[ah.next()]
ax.set_ylabel('Leave %')
ax.set_xlim([max(0, all_data[zh.next()].min()-all_data[mh.next()].min()/3),
all_data[ih.next()].max()+all_data[th.next()].max()/7])
results = sm.OLS(all_data['Leave votes'], sm.add_constant(orient)).fit()
X_plot = np.linspace(orient.min()-0.05, orient.max(), 100)
ax.plot(X_plot, X_plot*results.params[1] + results.params[0], )
for label, ori, leave in zip(all_data.index, orient, all_data['Leave votes']):
ax.annotate(label, xy=(ori, leave), xytext=(ori, leave+0.05),
arrowprops={'facecolor':'black', 'connectionstyle':'arc3,rad=0.3', 'arrowstyle':'simple'})
ax.scatter(orient, all_data['Leave votes'], s=area, c=colors, alpha=0.6)
ax.set_title(kh.next())
fig.subplots_adjust(hspace=space, wspace=space)
return fig
随着图形和轴创建方式的改变,问题得到了解决。如果有人能解释一下为什么会这样,那就很有趣了。在