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

วิธีทำ xtick Labels ให้เป็นรูปภาพ/สัญลักษณ์ง่ายๆ ใน Matplotlib


เพื่อทำ xtick labels ให้เป็นรูปวาดง่ายๆ ใน Matplotlib

  • ตั้งค่าขนาดรูปและ padding ระหว่าง subplots
  • กำหนดตำแหน่ง Y ของรูปวาด
  • สร้าง figure ใหม่ด้วย figure()
  • เพิ่ม Axes ด้วย add_subplot()
  • พลอตเส้นด้วย plot()
  • ตั้ง X-axis ticks ด้วย set_ticks()
  • ตั้ง tick labels ว่าง
  • เพิ่ม patch วงกลมและสี่เหลี่ยมด้วย add_patch() ใช้ class Circle() และ Rectangle()
  • แสดงรูปด้วย show()

ตัวอย่าง

import matplotlib.pyplot as plt
import matplotlib.patches as patches

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

y = -.75
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.get_xaxis().set_ticks([2, 4, 6, 8])
ax.get_xaxis().set_ticklabels([])
ax.add_patch(patches.Circle((2, y), radius=.2, clip_on=False, facecolor='red'))
ax.add_patch(patches.Circle((4, y), radius=.2, clip_on=False, facecolor='yellow'))
ax.add_patch(patches.Rectangle((6 - .1, y - .05), .2, .2, clip_on=False, facecolor='blue'))
ax.add_patch(patches.Rectangle((8 - .1, y - .05), .2, .2, clip_on=False, facecolor='green'))
plt.show()

ผลลัพธ์

วิธีทำ xtick Labels ให้เป็นรูปภาพ/สัญลักษณ์ง่ายๆ ใน Matplotlib