matplotlib轮廓在同一数据集上的contourf失败时起作用

时间:2017-02-22 13:45:02

标签: matplotlib contourf

我试图使用matlotlib的contour和contourf函数来虚拟化两个变量的函数。使用相同的数据,轮廓完美地工作但轮廓f产生有缺陷的图像。这是什么原因?

from numpy import exp, pi
import numpy as np

# function to be plotted
def R(n0,n1,y,d):
    r01 = -(n1-n0+y)/(n0+n1+y)
    t01 = 2*n0/(n0+n1+y)
    t10 = 2*n1/(n0+n1+y)
    r10 = -(n0-n1+y)/(n0+n1+y)
    return abs(r01 - t01*t10*exp(4j*pi*d)/(1+r10*exp(4j*pi*d)))**2.0

# meshgrid for plotting
xlist = np.linspace(0.0, 0.5, 101)
ylist = np.linspace(0.0, 6.0, 101)
X, Y = np.meshgrid(xlist, ylist)

# function values on the meshgrid
Z = []
for y in ylist:
    zslice = []
    for d in xlist:
        zslice.append(R(1.0,2.0,y,d))
    Z.append(zslice)

# plot -------------------------------------
import matplotlib.pyplot as plt
plt.figure()
levels = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
cp = plt.contour(X, Y, Z, levels) # works
cp = plt.contourf(X, Y, Z, levels) # fails=provides defective image
plt.colorbar(cp)
plt.clabel(cp, inline=True, fontsize=10)
plt.show()

1 个答案:

答案 0 :(得分:0)

您正在将标签设置为contourf。但是,它们应设置为contour

import matplotlib.pyplot as plt
plt.figure()
levels = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
cp2 = plt.contour(X, Y, Z, levels) 
cp = plt.contourf(X, Y, Z, levels) 
plt.colorbar(cp)
plt.clabel(cp2, inline=True, fontsize=10)
plt.show()

虽然基础逻辑并不完全清楚,但这解决了奇怪的contourf行为问题。