第十五章 生成数据
安装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)展示分析结果。代码语法需注意类定义、循环结构及库函数调用顺序。