我想在面板中动态显示由matplotlib
创建的图像。服务器端代码是:
...
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
...
def lineCurve2D(request):
x = np.linspace(-10, 10, 50)
y = np.linspace(-10, 10, 50)
x,y = np.meshgrid(x, y)
z = x**2 + 3*y**2 + x*y - 5*x + 3*y
fig = Figure()
plt.contour(x, y, z)
canvas = FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
我应该说,如果我在python shell中使用plt.show()
,那么我会看到一个很好的图像。
接下来,在客户端,我的代码如下所示:
function lineCurve2D(me){
Ext.Ajax.request({
url:'/myapp/lineCurve2D',
method:'GET',
success:function(res,req){
var plot=me.down('#LineCurve2D'); // it is a fieldset inside my panel
plot.items.each(function(el){
el.destroy(); // I destroy what was previously added
});
plot.add({xtype:'panel',layout:'fit',html:'<img src="data:image/png;base64,'+res.responseText+'"/>'}) // main problem
}
});
}
这是触发django返回图像的功能。返回时,它会在我的面板中创建图像。但是,我现在看到的是一个“空”图像,好像它的来源不正确。