Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách chèn thanh tỷ lệ (scale bar) vào bản đồ trong Matplotlib

Để thêm thanh tỷ lệ (scale bar) vào bản đồ/ảnh trong Matplotlib, ta dùng class AnchoredSizeBar từ mpl_toolkits.axes_grid1.anchored_artists.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo dữ liệu ảnh ngẫu nhiên.
  • Hiển thị ảnh bằng imshow().
  • Lấy axes hiện tại bằng gca().
  • Tạo scalebar bằng AnchoredSizeBar(ax.transData, length, label, loc).
  • Thêm artist vào axes bằng add_artist().
  • Tắt trục tọa độ.
  • Hiển thị bằng show().

Ví dụ

from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.random.rand(5, 5)
img = plt.imshow(data, cmap="YlGnBu")
ax = plt.gca()
scalebar = AnchoredSizeBar(ax.transData, 1, "1 Meter", 9)
ax.add_artist(scalebar)
ax.axis('off')
plt.show()

Kết quả

Cách chèn thanh tỷ lệ (scale bar) vào bản đồ trong Matplotlib