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

วิธีสร้างแผนภูมิเส้น (Line Chart) ด้วย Matplotlib

ในการสร้างแผนภูมิเส้นด้วย matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้:

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
  • สร้างลิสต์ของปี (years) และการเติบโตของประชากร (population growth)
  • วาด years และ population บนเส้นด้วยเมธอด plot()
  • เพื่อแสดงรูป ใช้เมธอด show()

ตัวอย่าง

from matplotlib import pyplot as plt

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

years = [1901, 1911, 1921, 1931, 1941, 1951,
         1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66,
              361.09, 439.23, 548.16, 683.33, 846.42, 1028.74]

plt.plot(years, population, color='red', marker='o')
plt.show()

ผลลัพธ์

วิธีสร้างแผนภูมิเส้น (Line Chart) ด้วย Matplotlibวิธีสร้างแผนภูมิเส้น (Line Chart) ด้วย Matplotlib