import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
# 生成网格
X,Y = np.meshgrid(x,y)
# contourf 会在等高线之间进行填充
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap='hot')
# contour 仅仅是画出等高线
C = plt.contour(X,Y,f(X,Y),8,colors='black',linewidth=.4)
# 添加数据标签
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()
对比contourf与contour的区别
在等高线之间填充颜色
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
# 生成网格
X,Y = np.meshgrid(x,y)
# contourf 会在等高线之间进行填充
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap='hot')
plt.xticks(())
plt.yticks(())
plt.show()
只绘制出等高线
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
# 生成网格
X,Y = np.meshgrid(x,y)
# contour 仅仅绘制出等高线
C = plt.contour(X,Y,f(X,Y),8,cmap='hot',linewidth=.5)
# 添加数据标签
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()