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

วิธี Annotate ปลายเส้นกราฟด้วย Python และ Matplotlib

การทำ Annotation ที่ปลายเส้นกราฟ

ใช้ annotate() วางข้อความที่ตำแหน่งสุดท้ายของแต่ละเส้นใน DataFrame plot

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • กำหนดจำนวนแถว rows
  • สร้าง DataFrame ข้อมูลสุ่ม และคำนวณ cumsum()
  • พล็อต DataFrame ด้วย plot()
  • วนลูป ax.lines และ column names
  • ดึงค่า y สุดท้ายของแต่ละเส้น
  • ใช้ annotate() พร้อม xycoords และ textcoords
  • วาง legend และแสดงผล

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

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

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

rows = 75
df = pd.DataFrame(np.random.randint(-5, 5, size=(rows, 3)), columns=['A', 'B', 'C'])
df = df.cumsum()

ax = df.plot()
for line, name in zip(ax.lines, df.columns):
    y = line.get_ydata()[-1]
    ax.annotate(name, xy=(1, y), xytext=(6, 0),
                color=line.get_color(), xycoords=ax.get_yaxis_transform(),
                textcoords="offset points", size=14, va="center")

plt.legend(loc='lower left')
plt.show()

คำอธิบาย

  • xy=(1, y): ตำแหน่งใน axes coordinates (x=1 = ขวาสุด)
  • xycoords=ax.get_yaxis_transform(): x ใน axes coords, y ใน data coords
  • textcoords="offset points": xytext เป็น offset ใน points