我正在创建一个网页,显示我使用Django在matplotlib中创建的图形。该脚本本身运行良好,但由于某种原因它在Django中不起作用。
这是我得到的错误:
This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
我在第一行导入matplotlib.use(),如下所示:
import matplotlib
matplotlib.use('TkAgg')
from django.shortcuts import render
from django.http import HttpResponse
from pylab import figure, axes, pie, title
我使用matplotlib.use(' TkAgg)来解决我在Django中没有脚本时遇到的问题。我认为同样的解决方案可以在Django中运行,但它给了我一个错误。有人知道如何修复代码吗?
我的代码很长,所以我只提供它的代码片段。我的函数名称非常具有描述性,所以我认为您能够直观地理解一些函数(这是我的views.py文件):
def index(request):
noaaNmbr='11809'
#for right now, this is the only active region that I'm pulling data for. When I get the graph up and running, I will make it more interactive for the user so that he can
urlData = "http://www.lmsal.com/hek/hcr?cmd=search-events3&outputformat=json&instrument=IRIS&noaanum="+ noaaNmbr +"&hasData=true"
webUrl = urlopen(urlData)
counter = 0
data = webUrl.read().decode('utf-8')
hekJSON = json.loads(data)
getInfo(counter, hekJSON)
sort()
# Sorts the data from earliest to most recent
fig, ax = plt.subplots(figsize=(30, 30))
circle = Circle((0, 0), 980, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5)
ax.add_patch(circle)
# Creates circular representation of the sun on the graph because that's all I really need for now
plt.plot(xcen, ycen, color="red")
plt.plot(xcen, ycen, 'ro', color = 'blue')
#first plots the points in red, then draws lines between the points in blue
plt.xlim([setXMin(hekJSON), setXMax(hekJSON)])
plt.ylim([setYMin(hekJSON), setYMax(hekJSON)])
#sets the boundaries of the graph
ax.set_xticks(np.arange(setXMin(hekJSON), setXMax(hekJSON), 50))
ax.set_yticks(np.arange(setYMin(hekJSON), setYMax(hekJSON), 50))
#sets the ticks
for i in range(getNumberOfEntries(hekJSON)):
if xfov[i] != 0:
xStart = xcen[i] - xfov[i]/14
yStart = ycen[i] - yfov[i]/14
ax.add_patch(Rectangle((xStart, yStart), xfov[i]/7, yfov[i]/7, facecolor='none'))
plt.grid()
texts = fixAnnotations(createAnnotations(hekJSON, noaaNmbr))
adjust_text(texts, arrowprops=dict(arrowstyle="-", color='k', lw=0.5))
canvas = FigureCanvasAgg(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
return response