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

วิธีใช้ Marker รูปภาพ PNG/JPG แบบกำหนดเองในกราฟ Matplotlib


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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้างรายการ paths เก็บไดเรกทอรีของภาพ
  • สร้างรายการจุด (x และ y)
  • ใช้ subplots() สร้าง figure และชุด subplots
  • วนลูป zip ของ x, y และ paths เพื่อพล็อตภาพแทนจุด
  • สร้าง AnnotationBbox() พร้อมภาพและจุด (x, y)
  • วาง xticks และ yticks บนแกนทั้งสอง
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

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

ผลลัพธ์

วิธีใช้ Marker รูปภาพ PNG/JPG แบบกำหนดเองในกราฟ Matplotlib