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

วิธีเพิ่ม Legends ให้กราฟใน Python Matplotlib

บทนำ

Legend ช่วยให้อ่านข้อมูลในกราฟเข้าใจง่ายขึ้น Matplotlib รองรับ legend หลายรูปแบบ และ annotation เพื่อเน้นจุดสำคัญ

ขั้นตอน

  1. ติดตั้ง matplotlib: pip install matplotlib
  2. เตรียมข้อมูลยอดขายมือถือ 3 ยี่ห้อ 5 ปี
  3. แยกข้อมูลเป็นอาร์เรย์แต่ละยี่ห้อ
  4. วาด Bar chart กลุ่ม (grouped bar chart) ด้วย plt.bar หลายครั้ง เลื่อนตำแหน่งด้วย width
  5. เพิ่ม Annotation เน้นจุดสนใจ (เช่น ยอดขายลด 50%) ด้วย plt.annotate
  6. เพิ่ม Legend: plt.legend(labels, title='Manufacturers')
  7. ย้าย Legend นอกกราฟ: bbox_to_anchor=(1, 0.8) และ plt.subplots_adjust(right=1.2)
  8. บันทึกภาพ: plt.savefig('MobileSales.png')

โค้ดเต็ม

import matplotlib.pyplot as plt

mobile = ['Iphone', 'Galaxy', 'Pixel']
units_sold = (('2016',12,8,6), ('2017',14,10,7), ('2018',16,12,8),
              ('2019',18,14,10), ('2020',20,16,5))

IPhone_Sales = [iph for _, iph, _, _ in units_sold]
Galaxy_Sales = [gal for _, _, gal, _ in units_sold]
Pixel_Sales = [pix for _, _, _, pix in units_sold]
Years = [y for y, _, _, _ in units_sold]
Position = list(range(len(units_sold)))
Width = 0.2

plt.bar([p - Width for p in Position], IPhone_Sales, width=Width, color='green')
plt.bar([p for p in Position], Galaxy_Sales, width=Width, color='blue')
plt.bar([p + Width for p in Position], Pixel_Sales, width=Width, color='yellow')

plt.xticks(Position, Years)
plt.xlabel('Yearly Sales')
plt.ylabel('Unit Sales In Millions')

plt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12),
             horizontalalignment='center', arrowprops=dict(facecolor='red', shrink=0.05))

plt.legend(mobile, title='Manufacturers', bbox_to_anchor=(1, 0.8))
plt.subplots_adjust(right=1.2)
plt.savefig('MobileSales.png')