python数据可视化Matplotlib

1.绘制简单的折线图

python 复制代码
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt


input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth=3)   # 线条粗细

# 设置图表标题并给坐标轴加标签
ax.set_title("平方数", fontsize=24)
ax.set_xlabel("值", fontsize=14)
ax.set_ylabel("值的平方", fontsize=14)

# 设置刻度标记大小
ax.tick_params(axis='both', labelsize=14)
# 在代码中添加如下语句 ------ 设置字体为:SimHei(黑体)
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签(中文乱码问题)

plt.show()

效果图:

2.使用内置样式绘制散点图,自定义颜色,颜色映射,自动保存图片

python 复制代码
import matplotlib.pyplot as plt


x_values = range(1, 1001)
y_values = [x**2 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots()
# 颜色映射cmap=plt.cm.Blues
ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10)

#设置图标标题并给坐标轴加标签
ax.set_title("平方数", fontsize=24)
ax.set_xlabel("值", fontsize=14)
ax.set_ylabel("值的平方", fontsize=14)

# 设置每个坐标轴的取值范围
ax.axis([0, 1100, 0, 1100000])
# 设置刻度标记的大小
ax.tick_params(axis='both', which='major', labelsize=14)
# 正常显示中文
plt.rcParams['font.sans-serif'] = ['SimHei']

# 显示
# plt.show()
# 保存
plt.savefig('squares_plot.png', bbox_inches='tight')

结果:

3.随机漫步

random_walk.py

python 复制代码
from random import choice


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

    def fill_walk(self):
        while len(self.x_values) < self.num_point:
            # 决定前进方向以及沿这个方向前进的距离
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance

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

            # 拒绝原地踏步
            if x_step == 0 and y_step == 0:
                continue

            # 计算下一个点的x和y
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step

            self.x_values.append(x)
            self.y_values.append(y)

rw.visual.py

python 复制代码
import matplotlib.pyplot as plt
from random_walk import RandomWalk


while True:
    rw = RandomWalk(50_000)
    rw.fill_walk()

    plt.style.use('classic')
    fig, ax = plt.subplots(figsize=(16, 9))
    point_number = range(rw.num_point)
    ax.scatter(rw.x_values, rw.y_values, c=point_number, cmap=plt.cm.Blues, edgecolors='none', s=1)

    #突出起点和终点
    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

结果:美的像一朵云

相关推荐
狂小虎6 分钟前
亲测解决self.transform is not exist
python·深度学习
Python智慧行囊7 分钟前
Python 中 Django 中间件:原理、方法与实战应用
python·中间件·架构·django·开发
深科文库16 分钟前
构建 MCP 服务器:第 3 部分 — 添加提示
服务器·python·chatgpt·langchain·prompt·aigc·agi
蓝婷儿38 分钟前
6个月Python学习计划 Day 17 - 继承、多态与魔术方法
开发语言·python·学习
Mikhail_G1 小时前
Python应用变量与数据类型
大数据·运维·开发语言·python·数据分析
hello kitty w2 小时前
Python学习(7) ----- Python起源
linux·python·学习
站大爷IP2 小时前
Python文本序列的类型
python
千千寰宇2 小时前
[Java/Python] Java 基于命令行调用 Python
python·java se-jdk/jvm
yvestine3 小时前
自然语言处理——文本表示
人工智能·python·算法·自然语言处理·文本表示