web123456

Matplotlib 3D drawing, this article is enough

# matplotlib 3D drawing # 3D axes (which belong to the Axes3D class) are created by passing the projection="3d" keyword parameter to Figure.add_subplot: from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np x = np.arange(100) y = np.random.randint(0, 300, 100) z = np.random.randint(0, 200, 100) # 3D line diagram def line_3d(): # Wire fig = plt.figure() ax = fig.add_subplot(projection='3d') # c color, marker: style * snowflake ax.plot(xs=x, ys=y, zs=z, c="y", marker="*") plt.show() # 3D scatter plot def scatter_3d(): # Scatter plot fig = plt.figure() ax = fig.add_subplot(projection='3d') # s: the size of the marker marker # c: Color can be single, can be sequence # depthshade: Whether to color scatter marks for a depth look. Each call to scatter() will perform its depth shading independently. # marker: style ax.scatter(xs=x, ys=y, zs=0, zdir='z', s=30, c="g", depthshade=True, cmap="jet", marker="^") plt.show() def randrange(n, vmin, vmax): """ Helper function to make an array of random numbers having shape (n, ) with each number distributed Uniform(vmin, vmax). """ return (vmax - vmin) * np.random.rand(n) + vmin # 3D random color scatter plot def scatter_random_color_3d(): # Random color scatter plot fig = plt.figure() ax = fig.add_subplot(projection='3d') # c: Color can be single, can be sequence # ‘b’ blue, g’ green, ‘r’ red, ‘c’ cyan # ‘m’ magenta Purple, ‘y’ yellow Yellow, ‘k’ black Black, ‘w’white White colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'] c = np.repeat(colors, 15)[:100] ax.scatter(xs=x, ys=y, zs=0, zdir='z', s=30, c=c, depthshade=True, cmap="jet", marker="^") plt.show() # demo example # Set seeds to reproduce random values np.random.seed(19680801) fig = plt.figure() ax = fig.add_subplot(projection='3d') n = 100 # For each style, draw n random points # Define x in [23, 32], y in [0, 100], z in [zlow, zhigh]. for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]: xs = randrange(n, 23, 32) ys = randrange(n, 0, 100) zs = randrange(n, zlow, zhigh) ax.scatter(xs, ys, zs, marker=m) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show() # Wireframe def wireframe_3d(): fig = plt.figure() ax = fig.add_subplot(projection='3d') x = np.random.randint(-30, high=30, size=(50,)).reshape((25, 2)) y = np.random.randint(-30, high=30, size=(50,)).reshape((25, 2)) z = np.zeros(50).reshape((25, 2)) # c: Color # ‘b’ blue, g’ green, ‘r’ red, ‘c’ cyan # ‘m’ magenta Purple, ‘y’ yellow Yellow, ‘k’ black Black, ‘w’white White ax.plot_wireframe(x, y, z, color='m') plt.show() # demo example fig = plt.figure() ax = fig.add_subplot(projection='3d') # Get test data X, Y, Z = axes3d.get_test_data(0.05) # Draw a basic wireframe ax.plot_wireframe(X, Y, Z, color='c', rstride=10, cstride=10) plt.show() # Surface drawing, by default, will be shaded with solid colors, but it also supports color mapping by providing cmap parameters. # rcount and ccount kwargs both default to 50, which determines the maximum number of samples used in each direction. If the input data is large, it is downsampled (by slice) to these points. # To maximize rendering speed, set rstride and cstride as divisors of row count 1 and column count 1, respectively. For example, given 51 rows, rstride can be any divisor of 50. # Similarly, setting rstride and cstride equals 1 (or rcount and ccount equals rows and columns equals) can use the optimization path. def surface_3d(): # 3D Surface (Color Map) Demonstrate drawing 3D surfaces colored with warm and cold color maps. Make the surface opaque by using antialiased=False. import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as np fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) # Build data X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2) Z = np.sin(R) # Draw a surface diagram # Draw a 3D surface colored with a warm and cold color map. Make the surface opaque by using antialiased=False. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z-axis ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) # A StrMethodFormatter is used automatically ax.zaxis.set_major_formatter('{x:.02f}') # Add a color bar to display the color interval fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() # Draw a surface diagram # Draw a 3D surface colored with a warm and cold color map. Make the surface transparent by using antialiased=True. fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=True) # Customize the z-axis ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) # A StrMethodFormatter is used automatically ax.zaxis.set_major_formatter('{x:.02f}') # Add a color bar to display the color interval fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() # Triangle Surface Diagram def tri_surface_3d(): n_radii = 8 n_angles = 36 # Set the radius and angle to an arithmetic array (omit radius r=0 to eliminate duplication) # start, stop, n, endpoint The default endpoint is True, including stop, False, and does not include stop radii = np.linspace(0.125, 1.0, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)[..., np.newaxis] # Convert polar coordinates (radius, angle) to cartesian Cartesian coordinates (x, y) # (0, 0) Added manually at this stage, so points in the (x, y) plane will not be repeated x = np.append(0, (radii * np.cos(angles)).flatten()) y = np.append(0, (radii * np.sin(angles)).flatten()) # Calculate z to generate a Pringle surface z = np.sin(-x * y) ax = plt.figure().add_subplot(projection='3d') ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True) plt.show() # 3D line diagram line_3d() # 3D scatter plot scatter_3d() # 3D random color scatter plot scatter_random_color_3d() # Wireframe wireframe_3d() # Surface drawing, by default, will be shaded with solid colors, but it also supports color mapping by providing cmap parameters. surface_3d() # Triangle Surface Diagram tri_surface_3d()