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

วิธีเพิ่มตัวแปรใน plt.title() ของ Python Matplotlib

การนำค่าตัวแปรไปแสดงในหัวข้อกราฟ (title) ใน Matplotlib สามารถทำได้หลายวิธี โดยใช้ f-string (Python 3.6+) หรือ str.format() หรือการจัดรูปแบบแบบเก่า % formatting

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

  1. นำเข้า numpy และ matplotlib.pyplot
  2. สร้างข้อมูล X และตัวแปรพารามิเตอร์ (เช่น num = 2)
  3. คำนวณข้อมูล Y จากตัวแปร (เช่น y = num ** x)
  4. พลอตกราฟด้วย plt.plot()
  5. ตั้งค่าหัวข้อด้วย plt.title() โดยฝังตัวแปรเข้าไปในสตริง
  6. แสดงผลด้วย plt.show()

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

import numpy as np
from matplotlib import pyplot as plt

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

x = np.linspace(-1, 1, 10)
num = 2
y = num ** x

plt.plot(x, y, c='red')
plt.title(f"y=%d$^x$" % num)
plt.show()

วิธีการจัดรูปแบบสตริงต่างๆ

วิธีตัวอย่างหมายเหตุ
f-string (แนะนำ)plt.title(f"y = {num}^x")Python 3.6+ อ่านง่าย เร็วที่สุด
str.format()plt.title("y = {}^x".format(num))Python 2.7+ รองรับการจัดรูปแบบซับซ้อน
% formattingplt.title("y = %d^x" % num)แบบเก่า ยังใช้ได้ แต่ไม่แนะนำ

การใช้ LaTeX ใน Title


# ใช้ raw string r"" สำหรับ LaTeX
plt.title(rf"$y = {num}^x$")  # f-string + raw string
plt.title(r"$y = %d^x$" % num)  # % formatting + raw string

# ตัวอย่างซับซ้อน
params = {"a": 2.5, "b": -1.3}
plt.title(rf"$y = {params['a']:.1f}x^2 + {params['b']:.1f}x$")

การประยุกต์ใช้

เหมาะสำหรับการสร้างกราฟอัตโนมัติ (automated plotting) การวนลูปพลอตหลายกราฟด้วยพารามิเตอร์ต่างกัน หรือการสร้างรายงานที่หัวข้อต้องอัปเดตตามค่าที่คำนวณได้