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

วิธีรวมกราฟหลายกราฟใน Python ด้วย Matplotlib

บทนำ

Matplotlib อนุญาตให้เพิ่มมากกว่าหนึ่ง plot ในกราฟเดียว ในบทช่วยสอนนี้ จะแสดงวิธีนำเสนอข้อมูลใน plot เดียวกัน บนแกน Y สองแกน (dual axes)

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

  1. ติดตั้ง matplotlib ผ่าน command prompt: pip install matplotlib
  2. นำเข้าไลบรารี: import matplotlib.pyplot as plt
  3. เตรียมข้อมูล (ข้อมูลตัวอย่าง ไม่ได้มาจากสถิติจริง)
import matplotlib.pyplot as plt
# data prep
mobile = ['Iphone', 'Galaxy', 'Pixel']
# Data for mobile units sold for 4 Quarters in Million
units_sold = (('2016',12,8,6), ('2017',14,10,7), ('2018',16,12,8), ('2019',18,14,10), ('2020',20,16,5),)
  1. แยกข้อมูลเป็นอาร์เรย์แต่ละบริษัท
# data prep - splitting the data
Years, IPhone_Sales, Galaxy_Sales, Pixel_Sales = zip(*units_sold)
# set the position
Position = list(range(len(units_sold)))
# set the width
Width = 0.2
  1. สร้าง subplot แรก (2 แถว 1 คอลัมน์ ตำแหน่งที่ 1)
plt.subplot(2, 1, 1)
  1. สร้างแท่งกราฟ (bar) สำหรับ IPhone Sales
Iphone = plt.bar(Position, IPhone_Sales, color='green')
plt.ylabel('IPhone Sales')
plt.xticks(Position, Years)
  1. สร้างแกน Y ที่สอง (twinx) สำหรับ Samsung Galaxy Sales
plt.twinx()
Galaxy = plt.plot(Position, Galaxy_Sales, 'o-', color='blue')
plt.ylabel('Galaxy Sales')
plt.xticks(Position, Years)
  1. Plot Google Pixel Sales ใน subplot ที่สอง
plt.subplot(2, 1, 2)
plt.plot(Position, Pixel_Sales, color='yellow')
plt.gca().set_ylim(ymin=0)
plt.xticks(Position, Years)
  1. รวมโค้ดทั้งหมดและบันทึกกราฟ
import matplotlib.pyplot as plt

# data prep
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),)

# split data
Years, IPhone_Sales, Galaxy_Sales, Pixel_Sales = zip(*units_sold)
Position = list(range(len(units_sold)))
Width = 0.2

plt.subplot(2, 1, 1)
Iphone = plt.bar(Position, IPhone_Sales, color='green')
plt.ylabel('IPhone Sales')
plt.xticks(Position, Years)

plt.twinx()
Galaxy = plt.plot(Position, Galaxy_Sales, 'o-', color='blue')
plt.ylabel('Galaxy Sales')
plt.xticks(Position, Years)

plt.subplot(2, 1, 2)
plt.plot(Position, Pixel_Sales, color='yellow')
plt.ylabel('Pixel Sales')
plt.gca().set_ylim(ymin=0)
plt.xticks(Position, Years)

# plt.show()
plt.savefig('CombiningGraphs.png', dpi=72)

ผลลัพธ์จะได้ไฟล์รูปภาพ CombiningGraphs.png ที่รวมกราฟแท่ง (IPhone), เส้น (Galaxy) บนแกน Y สองแกนใน subplot แรก และกราฟเส้น (Pixel) ใน subplot ที่สอง