第十五章 生成數據??
安裝Matplotlib:通過pip install matplotlib命令安裝庫。繪制折線圖的核心語法為:????
import matplotlib.pyplot as plt??x_values = [1, 2, 3]??y_values = [1, 4, 9]??plt.plot(x_values, y_values, linewidth=2)??plt.title("Title", fontsize=14)??plt.xlabel("X", fontsize=12)??plt.ylabel("Y", fontsize=12)??plt.show()
修改線條粗細通過linewidth參數,顏色通過color參數(支持RGB元組或顏色名稱)。??
散點圖使用scatter()函數:??
plt.scatter(x, y, c='red', edgecolor='none', s=40)??
顏色映射通過cmap參數實現,例如`plt.cm.Blues`。自動保存圖表語法:??
plt.savefig('image.png', bbox_inches='tight')
隨機漫步模型基于隨機選擇方向(0-3對應四個方向),步長公式為:??
x_step = direction * distance,其中direction通過random.choice([1, -1])確定,distance通過random.randint(0, 4)生成。??
使用Plotly模擬擲骰子需安裝plotly庫。Die類定義骰子面數,擲骰子方法為:??
from random import randint
class Die: def __init__(self, sides=6): self.sides = sides def roll(self): return randint(1, self.sides)
概率分析通過統計頻率實現,直方圖繪制使用Bar類。??
第十六章 下載數據??
處理CSV文件使用csv模塊:??
import csv
with open('data.csv') as f: reader = csv.reader(f) header_row = next(reader)
提取溫度數據并轉換為數值:??
highs = [int(row[1]) for row in reader]
日期處理依賴datetime模塊:??
from datetime import datetime
date = datetime.strptime('2025-03-30', '%Y-%m-%d')
JSON數據處理使用json模塊:??
import json
with open('data.json') as f: data = json.load(f)
提取地理坐標并繪制散點圖:??
lons = [item['lon'] for item in data]
lats = [item['lat'] for item in data]
plt.scatter(lons, lats, s=10)
顏色和尺寸定制通過參數`c`和`s`實現,例如:??
plt.scatter(lons, lats, c=values, cmap=plt.cm.Reds, s=population/100)
關鍵公式:??
1. 隨機漫步步長計算:x_step = direction * distance
2. 骰子概率分布:頻率=出現次數/總次數??
3. 數據歸一化:color_value = (value - min_value) / (max_value - min_value)
合并兩章后,技術流程為:首先生成模擬數據(隨機漫步、骰子),再處理外部數據(CSV、JSON),最后通過可視化工具(Matplotlib、Plotly)展示分析結果。代碼語法需注意類定義、循環結構及庫函數調用順序。