Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแทรกแท็บมาตรวัด (Scale Bar) ในแผนที่ด้วย Matplotlib


ใช้คลาส AnchoredSizeBar() เพื่อสร้างออบเจ็กต์แท็บมาตรวัด

ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้างข้อมูลสุ่มด้วย numpy
  • ใช้เมธอด imshow() แสดงข้อมูลเป็นภาพ
  • ดึงแกนปัจจุบันด้วย gca()
  • วาดแท็บมาตรวัดแนวนอนพร้อมป้ายชื่อกึ่งกลางด้านล่าง
  • เพิ่ม scalebar artist เข้าไปในแกนปัจจุบัน
  • ปิดการแสดงแกน
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

ตัวอย่างโค้ด

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()

ผลลัพธ์

วิธีแทรกแท็บมาตรวัด (Scale Bar) ในแผนที่ด้วย Matplotlib