第15章 · 生成数据

项目2数据可视化第1阶段:使用matplotlib绘制折线图和散点图,模拟随机漫步。

知识点 代码示例 章节测验(2 题)

知识点讲解

matplotlib基础绘图

matplotlib是Python最流行的数据可视化库。核心用法:plt.plot(x, y) 绘制折线图、plt.scatter(x, y) 绘制散点图,配合 plt.title()plt.xlabel()plt.ylabel()plt.show() 完善并展示图表。

import matplotlib.pyplot as plt
squares = [1, 4, 9, 16, 25]
plt.plot(squares)
plt.show()

随机漫步

随机漫步是模拟随机过程的经典案例:从原点出发,每次随机选择一个方向移动一步,重复上千次得到一条路径。使用choice模块的 randintchoice 决定移动方向,用散点图把整条路径绘制出来,并用颜色渐变表示先后顺序,效果非常直观。

代码示例

matplotlib绘图

演示折线图与散点图。

import matplotlib.pyplot as plt

squares = [1, 4, 9, 16, 25]
plt.plot(squares, linewidth=3)
plt.title("平方数", fontsize=24)
plt.xlabel("值", fontsize=14)
plt.ylabel("平方", fontsize=14)
plt.show()

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.scatter(x, y, s=100)
plt.show()

随机漫步

演示随机漫步模拟。

from random import choice

class RandomWalk:
    def __init__(self, num_points=5000):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            x_step = choice([1, -1]) * choice([0, 1, 2, 3, 4])
            y_step = choice([1, -1]) * choice([0, 1, 2, 3, 4])
            self.x_values.append(self.x_values[-1] + x_step)
            self.y_values.append(self.y_values[-1] + y_step)

rw = RandomWalk()
rw.fill_walk()
print(f"共{rw.num_points}个点,x范围: {min(rw.x_values)}~{max(rw.x_values)}")