1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 #定义计算高度的函数 5 def f(x,y): 6 return (1 - x/2 + x**5 +y**3) * np.exp(-x**2 - y**2) 7 8 n = 256 9 x = np.linspace(-3, 3, n) 10 y = np.linspace(-3, 3, n) 11 #核心函数是plt.contourf(),但在这个函数中输入的参数是x,y对应的网格数据以及此网格对应的高度值 12 #因此我们调用np.meshgrid(x,y)把x,y值转换成网格数据 13 X, Y = np.meshgrid(x, y) 14 15 #plt.contourf 与 plt.contour 区别: 16 # f:filled,也即对等高线间的填充区域进行填充(使用不同的颜色) 17 # contourf:将不会再绘制等高线(显然不同的颜色分界就表示等高线本身) 18 19 #use plt.contourf to filling contours(轮廓) 20 #X, Y and value for (X ,Y) point 21 plt.contourf(X, Y,f(X, Y), 8, alpha = 0.75, cmap = plt.get_cmap('rainbow')) 22 23 #use plt.contour to add contour lines 24 C = plt.contour(X, Y,f(X, Y), 8, colors = "black", linewidth = .5) 25 #关于cmap颜色选择,参考 https://matplotlib.org/examples/color/colormaps_reference.html 26 27 #adding label(为等高线上注明等高线的含义) 28 plt.clabel(C, inline = True, fontsize = 10) 29 30 plt.xticks(()) 31 plt.yticks(()) 32 33 plt.show()
1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 # image data 5 a = np.array([0.313660827978, 0.365348418405, 0.423733120134, 6 0.365348418405, 0.439599930621, 0.525083754405, 7 0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3) 8 9 #reshape()是数组对象中的方法,用于改变数组的形状。具体用法参考博文:https://blog.csdn.net/qq_28618765/article/details/78083895 10 11 #plt.imshow()参数设置参考 https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html 12 plt.imshow(a, interpolation='nearest', cmap='cool', origin='upper') 13 #参数interpolation为边界的模糊度或者图片的模糊度,参考博文 https://blog.csdn.net/qq_41634283/article/details/84933753 14 #参数origin: {'upper', 'lower'}, optional 15 # 将数组的[0,0]索引放置在轴的左上角或左下角。约定“上”通常用于矩阵和图像。如果未给出,则使用rcparams[“image.origin”],默认为“upper”。 16 17 plt.colorbar(shrink=.92) 18 #给figure添加颜色条或者渐变条,参考博文 https://www.jianshu.com/p/d97c1d2e274f 19 #colorbar()参数设置参考https://matplotlib.org/api/_as_gen/matplotlib.pyplot.colorbar.html 20 21 plt.xticks(()) 22 plt.yticks(()) 23 24 plt.show()
1 import numpy as np 2 import matplotlib.pyplot as plt 3 from mpl_toolkits.mplot3d import Axes3D #导入绘制3D数据的模块 4 5 fig = plt.figure() 6 ax = Axes3D(fig) 7 # X, Y value 8 X = np.arange(-4, 4, 0.25) 9 Y = np.arange(-4, 4, 0.25) 10 X, Y = np.meshgrid(X, Y) #np.meshgrid(x,y)把x,y值转换成网格数据 11 # height value 12 Z = np.sin(np.sqrt(X ** 2 + Y ** 2)) 13 14 ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'), edgecolor = "black") 15 #plot_surfac()参数设置参考 https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html 16 # *X*, *Y*, *Z*:Data values as 2D arrays 17 # *rstride* :Array row stride (step size), defaults to 10 18 # *cstride*:Array column stride (step size), defaults to 10 19 # *cmap*:A colormap for the surface patches. 20 ax.contourf(X, Y, Z, zdir = "z", offset = -2, cmap = "rainbow" ) 21 22 ax.set_zlim(-2, 2) 23 24 plt.show()