3D图形的绘制

it2025-02-28  25

一.3D可视化图表

1.3D柱状图、3D直方图

import random import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for z in range(1, 4): xs = range(1, 9) ys = 10 * np.random.rand(8) color = plt.cm.plasma(random.choice(range(plt.cm.plasma.N))) #zdir判断方向 ax.bar(xs, ys, zs=z, zdir='y', color=color) plt.show() #3D直方图 import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D np.random.seed(20190415) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x, y = np.random.rand(2, 100) * 4 hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]]) xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij") xpos = xpos.ravel() ypos = ypos.ravel() zpos = 0 dx = dy = 0.5 * np.ones_like(zpos) dz = hist.ravel() ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='lightgreen', zsort='average') plt.show()

2.3D相框图、3D曲面图、3D三翼面图

#线框图 from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y, Z = axes3d.get_test_data(0.04) ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show() #曲面图 import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') r = np.linspace(0, 1.25, 50) p = np.linspace(0, 2*np.pi, 50) R, P = np.meshgrid(r, p) Z = ((R**2 - 1)**2) X, Y = R*np.cos(P), R*np.sin(P) ax.plot_surface(X, Y, Z, cmap=plt.cm.YlGnBu_r) plt.show() #三翼曲面图 import numpy as np import matplotlib.pyplot as plt import matplotlib.tri as mtri from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() u = np.linspace(0, 2.0 * np.pi, endpoint=True, num=50) v = np.linspace(-0.5, 0.5, endpoint=True, num=10) u, v = np.meshgrid(u, v) u, v = u.flatten(), v.flatten() x = (1 + 0.5 * v * np.cos(u / 2.0)) * np.cos(u) y = (1 + 0.5 * v * np.cos(u / 2.0)) * np.sin(u) z = 0.5 * v * np.sin(u / 2.0) tri = mtri.Triangulation(u, v) ax = fig.add_subplot(111, projection='3d') ax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap=plt.cm.Spectral) ax.set_zlim(-1, 1) plt.show()

二.创建动画

from matplotlib import pyplot as plt from matplotlib import animation import numpy as np fig, ax = plt.subplots() x = np.arange(0, 2*np.pi, 0.01) line, = ax.plot(x, np.sin(x)) def animate(i): line.set_ydata(np.sin(x + i/10.0)) return line, def init(): line.set_ydata(np.sin(x)) return line, ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init, interval=20, blit=False) #plt.show() #生成mp4文件 ani.save('Sin(x).mp4', fps=30, extra_args=['-vcodec', 'libx264'], writer='ffmpeg_file')

来源:《python数据分析与可视化》

最新回复(0)