#!/usr/bin/env python # coding: utf-8 # ##内容索引 # # 1. 动画 --- 动画模块animation、FuncAnimation函数 # 1. dsafa # 1. 三维绘图 --- Axes3D对象、plot_surface函数 # 1. 等高线图 --- contour函数、contourf函数 # # In[7]: get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # ##1. 动画 # Matplotlib提供了动画功能,有专门的动画模块。我们需要定义一个回调函数,用于定期更新屏幕上的内容。 # In[8]: fig = plt.figure() ax = fig.add_subplot(111) N = 10 x = np.random.rand(N) y = np.random.rand(N) z = np.random.rand(N) circles, triangles, dots = ax.plot(x, 'ro', y, 'g^', z, 'b.') ax.set_ylim(0,1) plt.axis('off') def update(data): circles.set_ydata(data[0]) triangles.set_ydata(data[1]) return circles, triangles def generate(): while True: yield np.random.rand(2, N) anim = animation.FuncAnimation(fig, update, generate, interval=500) plt.show() # ##2. 三维绘图 # 对于3D作图,我们需要一个和三维投影相关的Axes3D对象。 # 绘制简单的三维函数z = x^2 = y^2 # In[14]: from mpl_toolkits.mplot3d import axes3d from matplotlib import cm fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 使用meshgrid函数创建二维的坐标网络 u = np.linspace(-1,1,100) x, y = np.meshgrid(u, u) z = x**2 + y**2 # 指定行和列的步幅,以及绘制曲面所用的色彩表(color map) ax.plot_surface(x, y, z, rstride=4, cstride=4, cmap=cm.rainbow_r) plt.show() # In[16]: x # ##3. 绘制等高线图 # Matplotlib中的等高线3D绘图有两种风格,填充和非填充的。我们可以使用contour函数创建一般的等高线图。对于色彩填充的等高线图,可以使用contourf绘制。 # In[10]: fig = plt.figure(figsize=(3,5)) ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) u = np.linspace(-1, 1, 100) x, y = np.meshgrid(u, u) z = x**2 + y**2 ax1.contour(x, y, z) ax2.contourf(x, y, z) plt.show() # ##4. 结合三维绘图和等高线图 # In[11]: fig = plt.figure() ax = fig.gca(projection='3d') X, Y, Z = axes3d.get_test_data(0.05) ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3, cmap=cm.winter_r) # 绘制等高线 cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm) cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm) cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm) ax.set_xlabel('X') ax.set_xlim(-40, 40) ax.set_ylabel('Y') ax.set_ylim(-40, 40) ax.set_zlabel('Z') ax.set_zlim(-100, 100) plt.show() # In[ ]: