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

Data Visualization ด้วยกราฟหลากหลายรูปแบบใน Python

Python มีไลบรารี Data Visualization ที่ใช้ง่าย รองรับข้อมูลน้อยหรือมาก:

  • Matplotlib: พื้นฐาน ควบคุมรายละเอียดได้หมด
  • Pandas: Plot ตรงจาก DataFrame
  • Plotly: Interactive, web-based
  • Seaborn: Statistical visualization สวยงาม

ข้อมูลตัวอย่าง: ประชากรอินเดีย 2019 แยกตาม Variant

CountryYearVariantValue
India2019Medium1,368,737.513
India2019High1,378,419.072
India2019Low1,359,043.965
India2019Constant fertility1,373,707.838
India2019Instant replacement1,366,687.871
India2019Zero migration1,370,868.782
India2019Constant mortality1,366,282.778
India2019No change1,371,221.64
India2019Momentum1,367,400.614

กราฟพื้นฐาน

Line Plot

import matplotlib.pyplot as plt
Year = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]
India_Population = [1173108018,1189172906,1205073612,1220800359,1266344631,1309053980,1324171354,1339180127,1354051854,1368737513]
plt.plot(Year, India_Population)
plt.show()

Scatter Plot

plt.plot(Year, India_Population, 'o')  # เพิ่ม 'o' เพื่อทำ scatter
plt.show()

Histogram


import pandas as pd
import matplotlib.pyplot as plt

data = [
    ['India', 2019, 'Medium', 1368737.513],
    ['India', 2019, 'High', 1378419.072],
    ['India', 2019, 'Low', 1359043.965],
    ['India', 2019, 'Constant fertility', 1373707.838],
    ['India', 2019, 'Instant replacement', 1366687.871],
    ['India', 2019, 'Zero migration', 1370868.782],
    ['India', 2019, 'Constant mortality', 1366282.778],
    ['India', 2019, 'No change', 1371221.64],
    ['India', 2019, 'Momentum', 1367400.614],
]
df = pd.DataFrame(data, columns=['Country or Area', 'Year(s)', 'Variant', 'Value'])
df.hist()
plt.show()

กราฟพิเศษ

Pie Chart


import numpy as np
import matplotlib.pyplot as plt

n = 25
Z = np.ones(n)
Z[-1] *= 2.5
plt.axes([0.05, 0.05, 0.95, 0.95])
plt.pie(Z, explode=Z*.05, colors=['%f' % (i/float(n)) for i in range(n)],
        wedgeprops={"linewidth": 1, "edgecolor": "green"})
plt.gca().set_aspect('equal')
plt.xticks([]), plt.yticks([])
plt.show()

Polar Plot


import numpy as np
import matplotlib.pyplot as plt

ax = plt.axes([0.5,0.05,0.95,0.95], polar=True)
N = 25
theta = np.arange(0.0, 2.5*np.pi, 2.5*np.pi/N)
radii = 10*np.random.rand(N)
width = np.pi/4*np.random.rand(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)
for r,bar in zip(radii, bars):
    bar.set_facecolor(plt.cm.jet(r/10.))
    bar.set_alpha(0.5)
ax.set_xticklabels([])
ax.set_yticklabels([])
plt.show()

คำแนะนำเลือกไลบรารี

  • เริ่มต้น: Matplotlib + Pandas built-in plot
  • Interactive Dashboard: Plotly / Bokeh
  • Statistical plots: Seaborn
  • Geospatial: Folium / GeoPandas
  • 3D/Complex: Mayavi / PyVista