我一直在使用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(),但也使用"子图"导致plt.figure包含任何内容。但是,如果我删除该行而是放入
g = mpld3.fig_to_html(fig)
我收到错误
TypeError at /charts/
350 is not JSON serializable
有人可以帮我理解出了什么问题吗?
图表图片包括: