This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

preface

At the beginning of matplotlib module, only 2D graphics were supported. For example, we have learned to draw statistical charts such as line chart, bar chart and histogram, as well as multiple subgraphs and common graphics. The following examples to the article, for reference

  • The matplotlib module is divided into script layer, art layer and back-end, which helps to learn workflow

  • Matplotlib draws line charts: Pyplo.plot () draws a summary of the related properties of the line chart

  • Matplotlib draws bar charts: Pyplot.bar () draws a bar chart for summary description

  • Histogram drawn by matplotlib: Pyolot.hist () draws histogram properties for summary description

  • Matplotlib graphing: it introduces the common drawing methods of rectangles and circles

With the development of technology, Matplotlib module on the basis of 2D drawing, packaging a practical 3D drawing toolkit mplot3D to support us to draw 3D graphics faster.

In this issue, we will learn 3D rendering module Mplot3D in detail, Let’s go~

1. Mplot3d overview

Mplot3d library is the Axes object of 2D projection provided for 3D image drawing in matplotlib module, which can be used to draw scatter graph, surface graph, broken line graph, grid, etc.

  • Mplot3d characteristics

    • Mplot3d allows users to create simple 3D graphics of Matplotlib 2D drawings
    • The mplot3D method is easy to use and can be drawn directly using 2D methods
    • If 3D images share the same rendering engine as 2D images, the z-axis projection may be biased
    • Mplot3d styles can be personalized by changing the parameters
  • Mplot3d use

When we use the Mplot3D toolkit, we need to use from… Import to import the Axes3D class

from  mpl_toolkits.mplot3d import Axes3D
Copy the code

PS:

  • The PyPlot class cannot add content to 3D plots, process additional 3D information, etc., and must be created using Axes3D objects
  • Mplot3d is not mature enough to draw 3D graphics. Mayavi is recommended for complex 3D graphics scenes

2. Step of drawing 3D graphics

To provide 3D graph drawing in matplotlib module requires the combination of Axes3D object in Mplot3D and Pyplot method, so there are the following steps to draw 3D graph

  • Import the Axes3D classes in matplotlib.pyplot and mpl_ToolKits. Mplot3d
import matplotlib.pyplot as plt
from  mpl_toolkits.mplot3d import Axes3D
Copy the code
  • Create a FIG canvas object using Pyplot.figure
fig = plt.figure()
Copy the code
  • Create a Axes object with 3D coordinates on the FIG canvas

    • Approach 1: Create a subimage using Projection =’3D’
    ax = fig.add_subplot(projection='3d')
    Copy the code
    • Method 2: Call the Axes3D class to create the object
    ax = Axes3D(fig)
    Copy the code
  • Call numpy.random or numpy.arange() to prepare x and y data

x = np.arange(-5.5.0.25)
y = np.arange(-5.5.0.25)
Copy the code
  • Call numpy.meshGrid () to map x and y
x,y = np.meshgrid(x,y)
Copy the code
  • Calculate Z axis data according to x and Y matrix data as required, such as calling numpy.sin() and cos() functions
R = np.sqrt(x**2+y**2)
z = np.cos(R)
Copy the code
  • Axes object called Pyplot to draw graphs and graphs, such as calling contour and plot_surface()
ax.plot_surface(x,y,z,rstride=1,cstride=1,alpha=0.5,cmap=cm.coolwarm)

ax.contour(x,y,z,zdir='z',offset=-2)
Copy the code
  • The Axes object calls the xlim,ylim,zlim methods to set the x, Y, and Z ranges
ax.set_zlim(-2.2)
Copy the code
  • Finally, pyplot.show() is called to show the drawn image
plt.show()
Copy the code
  • The result is shown in the figure below

3. Draw 3D scatter diagram

  • Use numpy. Arange () | numpy. Random. The randint () to the x, y, z axis of the data
  • The Axes object calls the Scatter plot method to draw the scatter plot
x = np.arange(0.200)
y = np.arange(0.100)

x,y = np.meshgrid(x,y)

z = np.random.randint(0.200,size=(100.200))

yc = np.arctan2(x,y)

ax.scatter(x,y,z,c=yc,s=50,marker=".")
Copy the code

4. Draw a 3D line chart

  • Prepare x and y data using Np.linspace () and Np.sin ()
  • The Axes object calls the plot() line method to draw a line graph
x = np.linspace(0.1.100)
y = np.sin(x*2*np.pi)/2+0.5
ax.plot(x,y,zs=0,zdir="z")
Copy the code

5. Draw 3D bar charts

for z in range(0.3):

    x = np.arange(1.13)
    y = 1000*np.random.rand(12)
    color = plt.cm.Set2(random.choice(range(plt.cm.Set2.N)))
    ax.bar(x,y,zs=z,zdir="y",color=color,alpha=0.8)

ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
Copy the code

conclusion

In this issue, learn the steps of mplot3D library drawing 3D graphics provided by Matplotlib module, and at the same time, manually operate scatter graph, broken line and bar graph 3D graph.

For 3D graphics, Axes3D objects must be used for rendering. For complex 3D graphics, matplotlib rendering engine renders poorly, and Mayavi is officially recommended for processing.

That’s the content of this episode. Please give us your thumbs up and comments. See you next time