( 图表 ) 3D 散布图
这篇教学会介绍如何使用 matplotlib 将图表转换成 3D 的显示模式,并在 3D 图表里显示数据的 3D 散布图。
本篇使用的 Python 版本为 3.7.12,所有范例可使用 Google Colab 实作,不用安装任何软件 ( 参考:使用 Google Colab )
import matplotlib
要进行本篇的范例,必须先加载 matplotlib 函数库的 pyplot 模组,范例将其独立命名为 plt。
import matplotlib.pyplot as plt
启用 3D 图表
如果使用 fig = plt.figure() 的方式建立图表,只要额外设定 projection='3d',就能将图表的显示模式设定为 3D 图表。
参考:使用 3D 图表
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(6,6))
ax = plt.subplot(projection='3d') # 設定為 3D 圖表
plt.show()
加入 3D 散布图
使用 scatter() 方法,额外加入 z 的参数,就能在 3D 图表中画出散布图。
import matplotlib.pyplot as plt import random fig = plt.figure(figsize=(8,6)) ax = plt.subplot(projection='3d') x = [random.randint(0,100) for i in range(200)] # 取得 200 个 0~100 的随机整数 y = [random.randint(0,100) for i in range(200)] # 取得 200 个 0~100 的随机整数 z = [random.randint(0,100) for i in range(200)] # 取得 200 个 0~100 的随机整数 ax.scatter(x,y,z,s=50) plt.show()
多组数据的 3D 散布图
如果有多组数据,只要重复执行 scatter() 的方法,就能够在图表中加入不同数据的 3D 散布图。
import matplotlib.pyplot as plt
import random
fig = plt.figure(figsize=(10,8))
ax = plt.subplot(projection='3d')
x = [random.randint(0,100) for i in range(150)]
y = [random.randint(0,100) for i in range(150)]
z = [random.randint(0,100) for i in range(150)]
ax.scatter(x,y,z,s=90,c=z,cmap='Reds')
ax.scatter(y,z,x,s=90,c=x,cmap='Blues')
ax.scatter(z,x,y,s=90,c=y,cmap='Greens')
plt.show()
import matplotlib.pyplot as plt
import random
fig = plt.figure(figsize=(10,8))
ax = plt.subplot(projection='3d')
x1 = [random.randint(0,100) for i in range(5000)]
x2 = [random.randint(100,200) for i in range(5000)]
x3 = [random.randint(200,300) for i in range(5000)]
y = [random.randint(0,100) for i in range(5000)]
z = [random.randint(0,100) for i in range(5000)]
ax.scatter(x1,y,z,s=30,c=z,cmap='Reds')
ax.scatter(x2,y,z,s=30,c=z,cmap='Blues')
ax.scatter(x3,y,z,s=30,c=z,cmap='Greens')
plt.show()
微信扫码关注
抖音扫码关注