30 lines of Python code for 3D data visualization, which is amazing

Review 2D Mapping

Use the Sebel curve to make a 2d plot. This figure is realized by using the Matplotlib-based Path through the Seibel curve. Friends who are interested in the Seibel curve can learn more about it. In matplotlib, figure is the canvas, axes are the drawing area, and the fig.add_subplot() and plt.subplot() methods can all create subplots. The following is a drawing practice.

import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
#定义绘图指令与控制点坐标
Path = mpath.Path
# Path 控制坐标点绘制贝塞尔曲线
# 图形数据构造

# MOVETO表示将绘制起点移动到指定坐标
# CURVE4表示使用4个控制点绘制3次贝塞尔曲线
# CURVE3表示使用3个控制点绘制2次贝塞尔曲线
# LINETO表示从当前位置绘制直线到指定位置
# CLOSEPOLY表示从当前位置绘制直线到指定位置,并闭合多边形
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', alpha=0.5)
ax.add_patch(patch)
# plot control points and connecting lines
x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-')
ax.grid()
ax.axis('equal')
plt.show()

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

Heart-shaped renderings

3D Hat Figure 1

Matplotlib draws 3D graphics using mplot3d Toolkit, the mplot3d toolkit. To draw a 3D graph, you can create a subgraph, and then specify the projection parameter as 3d, and the returned ax is an Axes3D object.

import package:

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

The whole process of drawing:

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()

# 指定图形类型是 3d 类型
ax = fig.add_subplot(projection='3d')

# 构造数据
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)

# 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 colors.
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

Rendering effect:

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

hat figure 1

3D Hat Figure 2

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

fig = plt.figure()
# 指定图形类型为 3d 类型
ax = fig.add_subplot(111, projection='3d')
# X, Y value
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)

# 设置 x-y 平面的网格
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
# height value
Z = np.sin(R)

# rstride:行之间的跨度  cstride:列之间的跨度
# rcount:设置间隔个数,默认50个,ccount:列的间隔个数  不能与上面两个参数同时出现
#vmax和vmin  颜色的最大值和最小值
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))

# zdir : 'z' | 'x' | 'y' 表示把等高线图投射到哪个面
# offset : 表示等高线图投射到指定页面的某个刻度
ax.contourf(X,Y,Z,zdir='z',offset=-2)

# 设置图像z轴的显示范围,x、y轴设置方式相同
ax.set_zlim(-2,2)

plt.show()

![](https://p26-tt.byteimg.com/large/pgc-image/ef6b24531bd845feae3a63a38868c92d)

hat figure 2

3D Linear Diagram

3D linear plots are drawn using Axes3D.plot. The basic method of drawing: Axes3D.plot(xs, ys[, zs, zdir='z', *args, **kwargs])

Parameter Description:

Parameter description xs one-dimensional array, point x-axis coordinate ys one-dimensional array, point y-axis coordinate zs one-dimensional array, optional, point z-axis coordinate zdir optional, when drawing 2D data on the 3D axis, the data must be Passed in the form of xs, ys, if zdir is set to 'y' at this time, the data will be drawn on the xz axis plane, the default is 'z'**kwargs Other keyword parameters, optional, see matplotlib. axes.Axes.plot

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

# 依次获取画布和绘图区并创建 Axes3D 对象
fig = plt.figure()
ax = fig.gca(projection='3d')

# 第一条3D线性图数据
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z1 = np.linspace(-2, 2, 100)
r = z1**2 + 1
x1 = r * np.sin(theta)
y1 = r * np.cos(theta)

# 第二条3D线性图数据
z2 = np.linspace(-3, 3, 100)
x2 = np.sin(z2)
y2 = np.cos(z2)

# 绘制3D线性图
ax.plot(x1, y1, z1, color='b', label='3D Line1')
ax.plot(x2, y2, z2, 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()

The results show that:

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

Linear graph

3D Scatter Plot

The basic way to draw a 3D scatter plot is: Axes3D.scatter(xs, ys[, zs=0, zdir='z', s=20, c=None, depthshade=True, *args, **kwargs])

Parameter details:

Parameter description xs one-dimensional array, point x-axis coordinate ys one-dimensional array, point y-axis coordinate zs one-dimensional array, optional, point z-axis coordinate zdir optional, when drawing 2D data on the 3D axis, the data must be Passed in the form of xs, ys, if zdir is set to 'y' at this time, the data will be drawn on the xz axis plane, the default is 'z's scalar or array type, optional, the size of the mark, the default is 20c marked Color, optional, can be a single color or a color list Supports English color names and their abbreviations, hexadecimal color codes, etc. For more color examples, see the official website Color Demodepthshadebool Value, optional, default True, whether it is a scatter mark Shaded to give depth look **kwargs additional 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()

The result is shown as:

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

Scatter plot

Summarize

This article mainly introduces the use of the Python third-party library Matplotlib to draw 3D graphics. Of course, in addition to the ones demonstrated above, there are more rich graphics and functions waiting for you to explore. Compared with 2D graphics, 3D graphics can show one more dimension of data features, which will have a more intuitive effect when visualizing. In the actual data visualization process, we have to decide what form to display according to specific needs, and knowing more about some tools can make it easier for us. These powerful tools are also one of the great advantages of Python in data analysis and visualization.

At the end, I will also give you a python spree [Jiajun Yang: 419693945] to help you learn better!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324341581&siteId=291194637