Skip to the content.

安装 Matplotlib

python3 -m pip install --user matplotlib

绘制简单的折线图

import matplotlib.pyplot as plt

squares = [1, 4, 9, 16, 25]

fig, ax = plt.subplots()
ax.plot(squares)

plt.show()

修改标签文字和线条粗细

import matplotlib.pyplot as plt

squares = [1, 4, 9, 16, 25]

fig, ax = plt.subplots()
ax.plot(squares, linewidth=3)

# 设置图的标题并给坐标轴加上标签
ax.set_title("Square Numbers", fontsize=24)
ax.set_xlabel("Value", fontsize=14)
ax.set_ylabel("Square of Value", fontsize=24)

# 设置刻度标记的样式
ax.tick_params(labelsize=14)

plt.show()

矫正绘图

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

fig, ax = plt.subplots()
ax.plot(x, y)

plt.show()

使用内置样式

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

plt.style.use('seaborn-v0_8')
fig, ax = plt.subplots()
ax.plot(x, y)

plt.show()

使用 scatter() 绘制散点图并设置样式

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.scatter(2, 4)

plt.show()

使用 scatter() 绘制一系列点

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

fig, ax = plt.subplots()
ax.scatter(x, y, s=100)

plt.show()

自动计算数据

import matplotlib.pyplot as plt

x = range(1, 1001)
y = [i**2 for i in x]

fig, ax = plt.subplots()
ax.scatter(x, y, s=10)
ax.axis([0, 1100, 0, 1_100_000])

plt.show()

定制刻度标记

import matplotlib.pyplot as plt

x = range(1, 1001)
y = [i**2 for i in x]

fig, ax = plt.subplots()
ax.scatter(x, y, s=10)
ax.axis([0, 1100, 0, 1_100_000])
ax.ticklabel_format(style='plain')

plt.show()

定制颜色

import matplotlib.pyplot as plt

x = range(1, 1001)
y = [i**2 for i in x]

fig, ax = plt.subplots()
# ax.scatter(x, y, color='red', s=10)
ax.scatter(x, y, color=(0, 0.8, 0), s=10)
ax.axis([0, 1100, 0, 1_100_000])
ax.ticklabel_format(style='plain')

plt.show()

使用颜色映射

import matplotlib.pyplot as plt

x = range(1, 1001)
y = [i**2 for i in x]

fig, ax = plt.subplots()
ax.scatter(x, y, c=y, cmap=plt.cm.Blues, s=10)
ax.axis([0, 1100, 0, 1_100_000])
ax.ticklabel_format(style='plain')

plt.show()

自动保存绘图

import matplotlib.pyplot as plt

squares = [1, 4, 9, 16, 25]

fig, ax = plt.subplots()
ax.plot(squares)

plt.savefig('name.png', bbox_inches='tight')

随机游走

创建 RandomWalk 类

import random

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_direction = random.choice([-1, 1])
            x_distance = random.choice([0, 1, 2, 3, 4, 5])
            x_step = x_direction * x_distance

            y_direction = random.choice([-1, 1])
            y_distance = random.choice([0, 1, 2, 3, 4, 5])
            y_step = y_direction * y_distance

            # 下个随机点不能原地踏步
            if x_step == 0 and y_step == 0:
                continue

            # 根据坐标列表中最后一个点的坐标, 计算出下个随机点的真实坐标
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step

            # 将下个随机点的真实坐标尾插入坐标列表中
            self.x_values.append(x)
            self.y_values.append(y)

绘制图像

import matplotlib.pyplot as plt
from random_walk import RandomWalk

# 死循环, 模拟多次随机游走
while True:
    rw = RandomWalk()
    rw.fill_walk()

    plt.style.use('classic')
    fig, ax = plt.subplots(figsize=(10, 6), dpi=224)  # 参数用来调整尺寸以适应屏幕, 我的mac电脑的api是224
    point_numbers = range(rw.num_points)  # 用来进行颜色映射, edgecolors参数用来删除每个点的轮廓
    ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=1)
    ax.set_aspect('equal')  # 指定两条轴上刻度的间距必须相等

    # 重新绘制起点和终点
    ax.scatter(0, 0, c='green', edgecolors='none', s=100)
    ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)

    # 隐藏坐标轴
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    plt.show()

    keep_running = input("Make another walk? (y/n): ")
    if keep_running == 'n':
        break

使用 Plotly 模拟掷骰子

本节使用 Plotly 来生成交互式图形. Plotly 能生成在浏览器中显示的图形, 并且能够自适应. Plotly Express 是 Plotly 的众多子模块之一, 它是 Plotly 中用于可视化的高级 API.

安装 Plotly

python3 -m pip install --user plotly
python3 -m pip install --user pandas

创建 Die 类

from random import randint

class Die:
    def __init__(self, num_sides=6):
        self.num_sides = num_sides  # 表示骰子的面数, 默认为6面

    def roll(self):
        return randint(1, self.num_sides)  # 随机返回一面的点数

掷骰子 && 绘制直方图

import plotly.express as px

from die import Die

die1 = Die()
die2 = Die()

results = []
for roll_num in range(1000):
    result = die1.roll() + die2.roll()
    results.append(result)

frequencies = []
max_result = die1.num_sides + die2.num_sides
poss_results = range(2, max_result + 1)
for value in poss_results:
    frequency = results.count(value)
    frequencies.append(frequency)

# 设置图像标题和坐标轴标签
title = "Results of Rolling Two One D6 1,000 Times"
labels = {
    'x': 'Result',
    'y': 'Frequency of Result'
}
fig = px.bar(x=poss_results, y=frequencies, title=title, labels=labels)

fig.update_layout(xaxis_dtick=1)  # 设置x轴上刻度标记的间距为1, 让每个条形都加上标签

# fig.write_html('dice_visual.html')  # 将图像保存为HTML文件
fig.show()

本例掷了两枚骰子共 1000 次, 用 frequencies 统计出最小点数 2 到最大点数 12 出现的频率, 最后用 plotly 生成直方图.

本站所有文章转发 CSDN 将按侵权追究法律责任,其它情况随意。