Để dùng file ảnh (PNG/JPG) làm marker thay vì ký hiệu chuẩn, ta dùng AnnotationBbox và OffsetImage từ matplotlib.offsetbox.
Các bước
- Thiết lập figure size và autolayout.
- Chuẩn bị danh sách đường dẫn ảnh và tọa độ (x, y).
- Tạo figure, axes bằng subplots().
- Duyệt qua (x, y, path), đọc ảnh bằng plt.imread(), tạo OffsetImage và AnnotationBbox.
- Thêm artist vào axes.
- Đặt ticks cho trục x, y.
- Hiển thị bằng show().
Ví dụ
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
def getImage(path):
return OffsetImage(plt.imread(path, format="jpg"), zoom=.1)
paths = ['globe.jpg', 'settings.jpg', 'settings.jpg', 'globe.jpg']
x = [8, 4, 3, 6]
y = [5, 3, 4, 7]
fig, ax = plt.subplots()
for x0, y0, path in zip(x, y, paths):
ab = AnnotationBbox(getImage(path), (x0, y0), frameon=False)
ax.add_artist(ab)
plt.xticks(range(10))
plt.yticks(range(10))
plt.show()
Kết quả
