3.2 3D图形
3.2.1 三维折线图
🚩创建一个三维空间有两种方法:
方法一:
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D # 3D引擎 plt.rcParams['font.family'] = 'KaiTi' plt.rcParams['axes.unicode_minus'] = False x = np.linspace(0, 60, 300) y = np.sin(x) z = np.cos(x) fig = plt.figure(figsize = (9, 6)) # 二维图形 ax3 = Axes3D(fig) # 二维变成了三维 ax3.plot(x, y, z) # 3维折线图 ax3.set_xlabel('X') ax3.set_ylabel('Y') ax3.set_zlabel('Z')
方法二:
import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'KaiTi' plt.rcParams['axes.unicode_minus'] = False x = np.linspace(0, 60, 300) y = np.sin(x) z = np.cos(x) fig = plt.figure(figsize = (9, 6)) ax3 = plt.subplot(111, projection = '3d') ax3.plot(x, y, z) ax3.set_xlabel('X') ax3.set_ylabel('Y') ax3.set_zlabel('Z')
如果你觉得这个视角不好看,我们还可以调整视角:
import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'KaiTi' plt.rcParams['axes.unicode_minus'] = False x = np.linspace(0, 60, 300) y = np.sin(x) z = np.cos(x) fig = plt.figure(figsize = (9, 6)) ax3 = plt.subplot(111, projection = '3d') ax3.plot(x, y, z) ax3.set_xlabel('X') ax3.set_ylabel('Y') ax3.set_zlabel('Z') # 图形可以调整角度 # 第一个参数是 x,y轴的角度,第二个参数是z轴的角度 ax3.view_init(elev = 30, azim = -80)
3.2.2 三维散点图
import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'KaiTi' plt.rcParams['axes.unicode_minus'] = False x = np.linspace(0, 60, 300) y = np.sin(x) z = np.cos(x) fig = plt.figure(figsize = (9, 6)) ax3 = plt.subplot(111, projection = '3d') ax3.set_xlabel('X') ax3.set_ylabel('Y') ax3.set_zlabel('Z') # 散点图 x = np.random.randint(0, 60, size = 20) y = np.random.randn(20) z = np.random.randn(20) ax3.scatter(x, y, z, color = 'red')
3.2.3 三维柱状图
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D # 3D引擎 month = np.arange(1, 5) # 每个月 4周 每周都会产生数据 # 三个维度:月、周、销量 fig = plt.figure(figsize = (9, 6)) ax3 = Axes3D(fig) for m in month: # 每个月都要绘制条形图 ax3.bar(np.arange(1, 5), # 横坐标 np.random.randint(1, 10, size = 4), # 纵坐标 zs = m , zdir = 'x', # 在哪个方向上,一排排排列,默认为'z' alpha = 0.7, # alpha 透明度 width = 0.5) # 条形图的宽度 plt.rcParams['font.family'] = 'KaiTi' ax3.set_xlabel('月份', fontsize = 18, color = 'red') ax3.set_xticks(month) ax3.set_ylabel('周', fontsize = 18, color = 'red') ax3.set_yticks([1, 2, 3, 4]) ax3.set_zlabel('销量', fontsize = 18, color = 'green')