Để vẽ scatter plot 3D có colorbar, ta dùng ax.scatter() trên axes 3D và plt.colorbar() với đối tượng scatter trả về.
Các bước
- Thiết lập figure size và autolayout.
- Tạo figure và thêm axes 3D bằng add_subplot(projection="3d").
- Tạo dữ liệu xs, ys, zs ngẫu nhiên.
- Vẽ scatter: sc = ax.scatter(xs, ys, zs, c=xs, cmap="copper").
- Thêm colorbar: plt.colorbar(sc).
- Hiển thị bằng show().
Ví dụ
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
xs = np.random.rand(100)
ys = np.random.rand(100)
zs = np.random.rand(100)
sc = ax.scatter(xs, ys, zs, c=xs, cmap="copper")
plt.colorbar(sc)
plt.show()
Kết quả
