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

การสร้าง 100% Stacked Area Chart ด้วย Matplotlib

Stacked Area Chart แบบ 100% ใช้แสดงสัดส่วนของแต่ละหมวดหมู่ต่อรวมทั้งหมดในแต่ละช่วงเวลา เหมาะสำหรับข้อมูลประชากร ส่วนแบ่งตลาด หรือองค์ประกอบที่เปลี่ยนแปลงตามเวลา

ขั้นตอนการสร้าง

  1. ตั้งค่าขนาด Figure และ Padding
  2. สร้างข้อมูล Year และ Population โดยแทนที่ด้วย Dictionary
  3. สร้าง Figure และ Subplots
  4. วาด Stacked Area Plot ด้วย ax.stackplot()
  5. เพิ่ม Legend, Title, และ Axis Labels
  6. แสดงผลด้วย plt.show()

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

import matplotlib.pyplot as plt

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

year = [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2018]

population_by_continent = {
    'africa': [228, 284, 365, 477, 631, 814, 1044, 1275],
    'americas': [340, 425, 519, 619, 727, 840, 943, 1006],
    'asia': [1394, 1686, 2120, 2625, 3202, 3714, 4169, 4560],
    'europe': [220, 253, 276, 295, 310, 303, 294, 293],
    'oceania': [12, 15, 19, 22, 26, 31, 36, 39],
}

fig, ax = plt.subplots()

# สำหรับ 100% stacked ต้อง normalize ข้อมูลก่อน
# แต่ตัวอย่างนี้เป็น stacked ปกติ (ไม่ใช่ 100%)
ax.stackplot(year, population_by_continent.values(), 
             labels=population_by_continent.keys())

ax.legend(loc='upper left')
ax.set_title('World Population')
ax.set_xlabel('Year')
ax.set_ylabel('Number of people (millions)')

plt.show()

การทำให้เป็น 100% Stacked Area Chart

หากต้องการแสดงเป็นเปอร์เซ็นต์ (100% Stacked) ต้อง normalize ข้อมูลก่อน:


import numpy as np

# แปลงข้อมูลเป็น array
data = np.array(list(population_by_continent.values()))
# Normalize ให้แต่ละคอลัมน์รวมกันได้ 100%
data_normalized = data / data.sum(axis=0) * 100

ax.stackplot(year, data_normalized, 
             labels=population_by_continent.keys())
ax.set_ylabel('Percentage (%)')

ผลลัพธ์

กราฟจะแสดงพื้นที่สะสมของแต่ละทวีป ตลอดช่วงปี 1950-2018 สามารถเห็นแนวโน้มการเติบโตของประชากรโลกได้ชัดเจน