Để vẽ biểu đồ phân tán 3D trong Python với hue colormap và legend, ta thực hiện:
- Thiết lập kích thước hình và điều chỉnh khoảng đệm giữa và xung quanh subplots.
- Tạo điểm dữ liệu x, y, z dùng numpy.
- Tạo hình mới hoặc kích hoạt hình hiện có dùng figure().
- Lấy trục hiện tại, tạo nếu cần.
- Lấy hue colormap, định nghĩa palette.
- Vẽ điểm x, y, z dùng scatter().
- Đặt legend trên đồ thị.
- Hiển thị hình dùng show().
Ví dụ
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
fig = plt.figure()
ax = fig.gca(projection='3d')
cmap = ListedColormap(sns.color_palette("husl", 256).as_hex())
sc = ax.scatter(x, y, z, s=40, c=x, marker='o', cmap=cmap, alpha=1)
plt.legend(*sc.legend_elements(), bbox_to_anchor=(1.05, 1), loc=2)
plt.show()
Kết quả
