Review 2D drawing

Make a 2D diagram of the Siebel curve. This graph is achieved using a Path based on Matplotlib through the Siebel curve, those who are interested in Siebel curve can take a closer look. In matplotlib, figure is canvas, axes is plot area, and fig.add_subplot() and plt.subplot() can create subplots. The following is a graphic practice.

import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt fig, Ax = plt.subplots() # define the plotting instruction and control point coordinates Path = mpath CURVE3: Draw a line from the current position to the specified position # LINETO: draw a line from the current position to the specified position # CLOSEPOLY: draw a line from the current position to the specified position And closed polygons path_data = [(Path. MOVETO (1.88, 2.57)), (Path. CURVE4 (0.35, 1.1)), (Path. CURVE4 (1.75, 1.5)), (Path. CURVE4, (0.375, 2.0)), (Path. LINETO (0.85, 1.15)), (Path. CURVE4 (2.2, 3.2)), (Path) CURVE4, (3, 0.05)), (path.curve4, (2.0, -1.5)), (path.closepoly, (1.58, -2.57)),] codes,verts = zip(*path_data) Path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, facecolor='r', Plot control points and connecting lines x, y = zip(*path.vertices) line, = max.vertices (x, 0) y, 'go-') ax.grid() ax.axis('equal') plt.show()Copy the code
! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/9910dc33d983433ea9bb81cfb5e7d5bd)

Heart-shaped renderings

3D hat figure 1

Matplotlib draws 3D graphics using the Mplot3D Toolkit, or Mplot3D Toolkit. It is possible to create a 3D image by creating a subimage and setting the projection parameter to 3D and returning ax as an Axes3D object.

The import package:

from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from mpl_toolkits.mplot3d import Axes3D
Copy the code

Drawing process:

import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from mpl_toolkits. Mplot3d import Axes3D import numpy as np FIG = plt.figure() # X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.arange(-5, 5, 0.25) X, Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) # Plot the surface. 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)) Ax.zaxis. Set_major_formatter (FormatStrFormatter('%.02f')) # Add a Color bar which maps values to color.fig. Colorbar (surf, shrink=0.5, aspect=5) plt.show()Copy the code

Rendering effect:

! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/b99e5a9702354c26bd7145fc86f067a0)

Figure 1 hat

3D hat figure 2

Import numpy as NP import matplotlib.pyplot as PLT from mpl_toolkits. Mplot3d import Axes3D FIG = plt.figure() # Ax = FIG. Add_subplot (111, projection='3d') # X, Y value X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 5, X, y = np. Meshgrid (x, y = np) Y) R = np.sqrt(X ** 2 + Y ** 2) # height value Z = np.sin(R) # rstride: Ax. plot_surface(X, Y, Z, rstride=1, cstride=1, Cmap = PLT. Get_cmap (' rainbow ') # zdir: 'z' | 'x' | 'y' to which said the contour map projection surface # offset: Ax.contourf (X,Y,Z,zdir=' Z ',offset=-2) ax.set_zlim(-2,2) plt.showCopy the code
! [](https://p26-tt.byteimg.com/large/pgc-image/ef6b24531bd845feae3a63a38868c92d)

Hat in figure 2

3 d linear graph

The 3D linear plot is plotted using axes3d.plot. Plot (xs, ys[, zs, zdir=’z’, *args, **kwargs])

Parameter Description:

Parameter Description XS one-dimensional array, x coordinates of a point ys one-dimensional array, y coordinates of a point ZS One-dimensional array, z coordinates of a point zdir Optional. When 2D data is drawn on the 3D axis, the data must be passed as XS, ys. If zdir is set to ‘y’, Data will be drawn to the x – z axis plane, the default is “z” * * kwargs other keyword arguments, optional, can see matplotlib axes. The axes. The plot

Import numpy as NP import matplotlib.pyplot as PLT from mpl_toolkits. Mplot3d import Axes3D = plt.figure() ax = FIG. Gca (projection='3d') Max = FIG. Gca (projection='3d') 100) z1 = np.linspace(-2, 2, X1 = r * np. Sine (theta) y1 = r * np. Cos (theta) # Plot (x1, y1, z1, color='b', label='3D Line1') ax.plot(x2, y2, z2, color='b', label='3D Line1') Color ='r', label='3D Line2') # plt.title, plt.xlabel, plt.legend... ax.set_title('3D Line View', pad=15, fontsize='10') ax.set_xlabel('x ', color='r', fontsize='14') ax.set_ylabel('y ', color='g', fontsize='14') ax.set_zlabel('z ', color='b', fontsize='14') ax.legend() plt.show()Copy the code

The results show:

! [](https://p3-tt-ipv6.byteimg.com/large/pgc-image/a845d3958a7744a199c05c91b20a41c1)

The linear graph

3 d scatter plot

Scatter (xs, ys[, ZS =0, zDIR =’z’, S =20, C =None, depthShade =True, *args, **kwargs])

Parameter description:

Parameter Description XS one-dimensional array, x coordinates of a point ys one-dimensional array, y coordinates of a point ZS One-dimensional array, z coordinates of a point zdir Optional. When 2D data is drawn on the 3D axis, the data must be passed as XS, ys. If zdir is set to ‘y’, The data will be drawn on the X-Z axis plane, default to ‘Z’s scalar or array type, optional, tag size, default 20C tag color, optional, can be a single color or a list of colors support English color names and their abbreviation, hex color code, etc., See Color Demodepthshadebool for more Color examples, optional, default True, whether to Color scatter marks to provide depth appearance **kwargs other keywords

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

def randrange(n, vmin, vmax):

    return (vmax - vmin) * np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, c=c, marker=m)

ax.set_title('3D Diagram View', pad=15, fontsize='10')
ax.set_xlabel('x ', color='r', fontsize='14')
ax.set_ylabel('y ', color='g', fontsize='14')
ax.set_zlabel('z ', color='b', fontsize='14')

plt.show()
Copy the code

The result is:

! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/1677602698914e9989bf8787fe2f5789)

A scatter diagram

conclusion

This article focuses on using the Python third-party library Matplotlib to draw 3D graphics, but there are many more graphics and features to explore. Compared with 2D graphics, 3D graphics can show one more dimension of data features and have a more intuitive effect in visualization. In the actual data visualization process, we need to decide what form to display according to the specific needs, and more understanding of some tools can be more easily. These powerful tools are one of Python’s great strengths for data analysis and visualization.

Complete project code acquisitionClick on the blue font