5. Python數(shù)據(jù)可視化: 用Matplotlib繪制折線圖
1. Matplotlib環(huán)境配置與基礎準備
1.1 安裝與庫導入
在開始使用Matplotlib進行折線圖(Line Chart)繪制前,我們需要確保正確安裝核心庫及其依賴。推薦使用Python 3.8+版本環(huán)境:
# 通過pip安裝
pip install matplotlib numpy pandas
# 驗證安裝版本
import matplotlib
print(matplotlib.__version__) # 應輸出3.5.0+
典型導入方式遵循社區(qū)約定俗成的規(guī)范:
import matplotlib.pyplot as plt
import numpy as np
1.2 基礎繪圖原理
Matplotlib采用分層架構設計:
- Figure對象(Figure object):頂級容器,對應整個畫布
- Axes對象(Axes object):包含坐標軸和繪圖元素的子區(qū)域
- Artist對象:所有可見元素的基類
基礎繪圖流程遵循以下模式:
# 創(chuàng)建畫布和坐標系
fig, ax = plt.subplots()
# 生成示例數(shù)據(jù)
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 繪制折線圖
ax.plot(x, y)
# 顯示圖表
plt.show()
2. 折線圖核心繪制技術
2.1 數(shù)據(jù)準備與基本繪制
處理真實數(shù)據(jù)集時,我們常使用Pandas進行數(shù)據(jù)預處理。以某城市全年溫度數(shù)據(jù)為例:
import pandas as pd
# 創(chuàng)建模擬數(shù)據(jù)集
data = {
'month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
'temp': [5.3, 7.1, 12.5, 18.2, 23.8, 26.5]
}
df = pd.DataFrame(data)
# 基本折線圖繪制
plt.figure(figsize=(10,6))
plt.plot(df['month'], df['temp'],
marker='o',
linestyle='--',
color='#2c7bb6')
plt.title('Monthly Temperature Variation')
plt.xlabel('Month')
plt.ylabel('Temperature (°C)')
plt.grid(True)
plt.show()
該代碼生成圖表包含以下關鍵要素:
- 自定義圖表尺寸(10x6英寸)
- 圓形數(shù)據(jù)點標記(marker='o')
- 虛線連接樣式(linestyle='--')
- HSL顏色編碼(#2c7bb6)
2.2 多線對比可視化
對比多個數(shù)據(jù)序列時,需要優(yōu)化視覺區(qū)分度。以下是股票價格對比示例:
# 生成時間序列數(shù)據(jù)
dates = pd.date_range('2023-01-01', periods=30, freq='D')
stock_a = np.cumsum(np.random.randn(30)) + 50
stock_b = np.cumsum(np.random.randn(30)) + 45
# 繪制雙折線圖
fig, ax = plt.subplots(figsize=(12,7))
ax.plot(dates, stock_a, label='Company A', linewidth=2)
ax.plot(dates, stock_b, label='Company B', linestyle=':')
# 設置坐標軸格式
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
ax.set_ylabel('Price (USD)')
# 添加輔助元素
ax.legend()
ax.grid(alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
3. 高級定制化技巧
3.1 樣式引擎與主題定制
Matplotlib提供多種內(nèi)置樣式可供選擇:
print(plt.style.available) # 查看可用樣式
plt.style.use('seaborn-darkgrid') # 應用指定樣式
自定義樣式可通過修改rcParams實現(xiàn):
plt.rcParams.update({
'font.size': 12,
'axes.titlesize': 16,
'axes.labelpad': 10,
'grid.alpha': 0.5
})
3.2 動態(tài)數(shù)據(jù)可視化
對于實時數(shù)據(jù)監(jiān)控場景,可使用FuncAnimation實現(xiàn)動態(tài)更新:
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'r-')
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
ax.relim()
ax.autoscale_view()
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 4*np.pi, 128),
blit=True)
plt.show()
4. 性能優(yōu)化策略
4.1 大數(shù)據(jù)量處理
當處理超過10萬數(shù)據(jù)點時,建議:
- 使用Numpy數(shù)組替代Python列表
- 設置agg_limit參數(shù)控制渲染精度
- 關閉自動縮放功能
x = np.random.randn(100000)
y = np.cumsum(x)
plt.plot(y, rasterized=True) # 啟用柵格化
plt.rcParams['agg.path.chunksize'] = 10000 # 設置分段閾值
5. 真實案例:COVID-19數(shù)據(jù)趨勢分析
# 加載公開數(shù)據(jù)集
url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/data/time-series-19-covid-combined.csv'
df = pd.read_csv(url)
# 數(shù)據(jù)預處理
us_data = df[df['Country/Region'] == 'US']
us_data['Date'] = pd.to_datetime(us_data['Date'])
us_data = us_data.sort_values('Date')
# 創(chuàng)建雙軸圖表
fig, ax1 = plt.subplots(figsize=(14,8))
color = 'tab:red'
ax1.set_xlabel('Date')
ax1.set_ylabel('Confirmed Cases', color=color)
ax1.plot(us_data['Date'], us_data['Confirmed'], color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Deaths', color=color)
ax2.plot(us_data['Date'], us_data['Deaths'], color=color)
ax2.tick_params(axis='y', labelcolor=color)
plt.title('US COVID-19 Cases Trend')
plt.gcf().autofmt_xdate()
plt.show()
本案例展示了:
- 真實數(shù)據(jù)集的加載與清洗
- 時間序列數(shù)據(jù)的可視化處理
- 雙Y軸坐標系的實現(xiàn)方法
技術標簽
#Python數(shù)據(jù)可視化 #Matplotlib教程 #折線圖繪制 #數(shù)據(jù)可視化技巧 #Python編程