我一直在使用 Matplotlib 与 Django 一起使用 Python 开发一个项目。现在我只想在网页中显示图表。之前,我将图形保存为 PNG,然后图形就显示出来了。不幸的是,这禁用了我计划包含的一些交互功能。为了解决这个问题,我使用了 MPLD3 的函数 fig_to_html,我在其他示例中看到了该函数。但是,当我在自己的代码中使用该行时,屏幕上什么也没有出现。
这是我的代码:
def index(request):
# template = loader.get_template('')
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
chart = plt.figure()
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(round_multiple(setXMin(hekJSON),50), round_multiple(setXMax(hekJSON), 50), 50))
ax.set_yticks(np.arange(round_multiple(setYMin(hekJSON),50), round_multiple(setYMax(hekJSON), 50), 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()
g = mpld3.fig_to_html(chart)
return HttpResponse(g)
我目前的理论是,通过设置 chart = plt.figure() 但也使用“subplots”导致 plt.figure 不包含任何内容。但是,如果我删除该行并改为放置
g = mpld3.fig_to_html(fig)
我收到错误
TypeError at /charts/
350 is not JSON serializable
有人可以帮我理解出了什么问题吗?
图表图片包括: