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

วิธีเพิ่มข้อความตัวหนาแบบ Annotated ใน Matplotlib


ใช้การแทนที่ LaTeX สำหรับป้ายกำกับ

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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้างข้อมูล x และ y ด้วย numpy
  • สร้างรายการป้ายกำกับสำหรับแต่ละจุดกระจาย
  • พล็อต xpoints, ypoints ด้วย scatter() สีใช้ xpoints
  • วนลูป zip ของ labels, xpoints, ypoints
  • ใช้ annotate() พร้อม LaTeX แบบตัวหนาในลูป
  • ใช้เมธอด 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()

ผลลัพธ์

วิธีเพิ่มข้อความตัวหนาแบบ Annotated ใน Matplotlib