我有一个Django应用程序,它根据通过UI进行的选择在浏览器上绘制图像。每当UI发生变化时,都会调用JavaScript函数,并创建一个调用django视图。
每当我从浏览器更改UI时,一个新的Image由views.py中的函数创建,并作为HTTPResponse返回给Javascript,最终在浏览器上绘制图像。
这里的问题是旧图像没有被删除,并且在浏览器上绘制了一个新图像,如下图所示
我已经检查过所有计算都是在views.py中进行的,并且值会返回给模板。
views.py
class PlotTool(View):
@staticmethod
def kmeansPlot(request):
[X,labels] = cluster_kmeans(request.GET.get('value'))
color = ["g", "r", 'purple','olive','teal','orchid','darkorange']
size = [90] * len(X)
for i in xrange(len(X)):
plt.scatter(X[i][0], X[i][1], c=color[labels[i]],s=size[i])
#To Show Centroids on Plot
plt.title('Kmeans')
plt.grid(True)
# Store image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
response = HttpResponse(buffer.getvalue(), content_type="image/png")
return response
@staticmethod
def PCAPlot(request):
score,coeff,labels = pcaAnalysis()
xs = score[:,0]
ys = score[:,1]
n=coeff.shape[0]
scalex = 1.0/(xs.max()- xs.min())
scaley = 1.0/(ys.max()- ys.min())
plt.scatter(xs*scalex,ys*scaley)
for i in range(n):
plt.arrow(0, 0, coeff[i,0], coeff[i,1],color='r',alpha=0.5)
if labels is None:
plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color='g', ha='center', va='center')
else:
plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color='g', ha='center', va='center')
plt.title('PCA')
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("PC{}".format(1))
plt.ylabel("PC{}".format(2))
plt.grid()
# Store image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
response = HttpResponse(buffer.getvalue(), content_type="image/png")
return response
Python 2.7.10,Django 1.9 感谢任何帮助......谢谢
编辑:完整的Java脚本代码
<body>
<div class="container">
<div class="col-left">
<form action='#' method="get">
<div>
<label>No of Cluster</label>
</div>
<input id="slider1" type="range" class="myinput" value="3" min="2" max="10" step="1" onchange="callFun(dropdown1.value,this.value)" />
<div class="count"><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span style="border:none">10</span></div>
</form>
</div>
<div class="col-right">
<label>Select Clustering Method</label>
<select name="test" id="dropdown1" onchange="callFun(this.value,slider1.value)">
<option value="Kmeans Clustering" selected>Kmeans Clustering</option>
<option value="Birch Clustering">Birch Clustering</option>
<option value="PCA Plot">PCA Plot</option>
</select>
</div>
<div style="width:100%; float:left;margin-top:30px;">
<img id="im" src='{% url "kmeans_graph" %}' align="left" height="400" width="400" >
<p id="demo">3</p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/1.0.0/fetch.min.js"></script>
<script>
function callFun(value1,value2) {
if (value1 == 'Kmeans Clustering'){
var img_src = '{% url "kmeans_graph" %}'
document.getElementById("im").setAttribute("src",img_src + '?value=' + value2);
document.getElementById("demo").innerHTML =value2
}
else if(value1 == 'Birch Clustering'){
var img_src = '{% url "birch_graph" %}'
document.getElementById("im").setAttribute("src",img_src + '?value=' + value2);
document.getElementById("demo").innerHTML =value2
}
else{
var img_src = '{% url "pca_graph" %}'
document.getElementById("im").setAttribute("src",img_src + '?value=' + Math.random());
document.getElementById("demo").innerHTML ='pca_graph'
}
}
</script>
</body>
</html>
&#13;
答案 0 :(得分:0)
得到答案......
在views.py中
pylab.get_current_fig_manager().canvas
在上面的代码fig = Figure()
ax = fig.add_subplot(111)
#change all plt instances with ax
canvas=FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
中获取当前的图形管理器,它每次都是相同的,这就是为什么它正在绘制旧图像而不是创建新图像。所以我把代码更改为
package.json
这对我有用