以前,我对interference between multiple Matplotlib figures有问题。最终我被跟踪到一个问题,一些pyplot函数没有附加到它们的图形实例,但是可以在并行创建的其他一些图形实例中呈现。
这是一些示例代码:
from django.http import HttpResponse
from numpy import arange, meshgrid
from matplotlib.mlab import bivariate_normal
def show_chart(request):
delta = 0.025
x = arange(-3.0, 3.0, delta)
y = arange(-2.0, 2.0, delta)
X, Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10.0 * (Z2 - Z1)
from matplotlib.pyplot import figure, contour
fig1 = figure(figsize=(4, 4), facecolor='white')
contour(X, Y, Z)
response = HttpResponse(content_type='image/png')
fig1.savefig(response, format='png')
fig1.clear()
return response
上面示例中的轮廓pyplot函数可以在图1中呈现,但偶尔在并行生成的某些其他图中也可以呈现。太烦人了。有什么方法可以将轮廓pyplot函数附加到fig1吗?
最佳答案
您可以创建一个子图,然后调用该子图的contour
方法:
fig1 = figure(figsize=(4, 4), facecolor='white')
ax = fig1.add_subplot(111)
ax.contour(X, Y, Z)
plt.subplots
使得通过一次调用即可创建图形和子图方便:import matplotlib.pyplot as plt
fig, ax = plt.subplots()