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

วิธีทำเครื่องหมายหลายจุดด้วยข้อความเดียวใน Matplotlib

ในการเพิ่มข้อความ annotate ใน Matplotlib สำหรับหลายจุด เราสามารถทำตามขั้นตอนต่อไปนี้:

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
  • สร้างจุดข้อมูล x และ y ด้วย numpy
  • เพื่อตั้งค่า label สำหรับแต่ละจุดกระจาย ให้สร้างลิสต์ของ labels
  • วาด xpoints, ypoints ด้วยเมธอด scatter() สำหรับสี ใช้ xpoints
  • วนลูป zipped labels, xpoints และ ypoints
  • ใช้เมธอด annotate() ด้วยการแทนค่า LaTeX แบบ bold ใน for loop
  • เพื่อแสดงรูป ใช้เมธอด show()

ตัวอย่าง

import numpy as np
from matplotlib import pyplot as plt

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

xpoints = np.linspace(1, 10, 10)
ypoints = np.random.rand(10)
labels = ["%.2f" % i for i in xpoints]

plt.scatter(xpoints, ypoints, c=xpoints)

for label, x, y in zip(labels, xpoints, ypoints):
    plt.annotate(
        f"$\\bf{label}$", xy=(x, y), xytext=(-20, 20), textcoords='offset points',
        ha='center', va='bottom', arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))

plt.show()

ผลลัพธ์

วิธีทำเครื่องหมายหลายจุดด้วยข้อความเดียวใน Matplotlibวิธีทำเครื่องหมายหลายจุดด้วยข้อความเดียวใน Matplotlib