《Python编程:从入门到实践》学习记录(15)项目-数据可视化 matplotlib, pygal

简介: 《Python编程:从入门到实践》学习记录(15)项目-数据可视化 matplotlib, pygal
  • 安装可视化工具matplotlib
  • 一个数学会图库,可以绘制简单的图标,折线图,散点图。
  • 检查是否安装了matplotlib


image.png

安装matplotlib,必须使用pip3

  • pip3 install --user matplotlib


image.png

image.png



# 绘制折线图

import matplotlib.pyplot as plt
# X轴对应的数据
x_value_list = [1, 2, 3, 4, 5]
# Y轴对应的数据
squares = [1, 4, 9, 16, 25]
plt.plot(x_value_list, squares, linewidth=5)
# 设置图标的标题,并给坐标轴加上标签
plt.title("Square", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 设置刻度标记的大小
plt.tick_params(axis='both', labelsize=14)
plt.show()



image.png

# 绘制散点图


  • 在指定的xy坐标绘制一个点: scatter(x,y)

import matplotlib.pyplot as plt
x_list = list(range(101))
y_list = [x ** 2 for x in x_list]
plt.scatter(x_list, y_list, c='red', edgecolors='green', s=10)
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
# 横纵坐标的范围
plt.axis([0, 100, 0, 11000])
# 展示图片
# plt.show()
# 保存图片到文件
plt.savefig('s.png', bbox_inches='tight')


image.png



# 模拟随机漫步(散点图)


  • 生成随机x,y坐标点位 random_walk.py

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_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
            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step
            self.x_values.append(next_x)
            self.y_values.append(next_y)
  • 根据生成的随机点位绘图 rw_visual.py

import matplotlib.pyplot as plt
from data_show.walk.random_walk import RandomWalk
while True:
    rw = RandomWalk()
    rw.fill_walk()
    plt.scatter(rw.x_values, rw.y_values, s=15)
    plt.show()
    con_str = input("continue(y/n)?\n")
    if con_str == 'y':
        continue
    else:
        break


  • 结果


image.png

# 使用Pygal绘制矢量图



  • 安装 pip install --user pygal==1.7


image.png


  • 需求描述:掷一个点数为1-6的六面骰子,掷1000次,统计每个点数出现的次数,并将统计结果绘制成柱状svg图

from random import randint
import pygal
class Die:
    """骰子"""
    def __init__(self, num_sides=6):
        """
        初始化方法
        :param num_sides: 骰子的面数
        """
        self.num_sides = num_sides
    def roll(self):
        """
        掷骰子,Return random integer in range [a, b], including both end points.
        :return:
        """
        return randint(1, self.num_sides)
def draw(data_dict: dict):
    """
    绘图
    :param data_dict: 
    :return:
    """
    hist = pygal.Bar()
    hist.title = "投掷1000次6面筛子的结果统计"
    hist.x_labels = data_dict.keys()
    hist.x_title = "点数"
    hist.y_title = "点数对应的次数"
    hist.add('6面骰子', data_dict.values())
    # 导出问文件,扩展名必须为`.svg`
    hist.render_to_file('die_visual.svg')
die = Die()
result_list = []
# 掷骰子并保存结果
for i in range(1000):
    result_list.append(die.roll())
# 点数:出现次数
point_count_dict = {}
# 分析每个点数出现的次数
for i in range(1, die.num_sides + 1):
    point_count_dict[i] = result_list.count(i)
# 绘图
draw(point_count_dict)


  • 结果:(使用浏览器打开svg文件)
  • 各个点数出现的概率基本随机且相近


image.png

  • 需求:同时投掷两个6面骰子,统计两个骰子的结果之和

from random import randint
import pygal
class Die:
    """骰子"""
    def __init__(self, num_sides=6):
        """
        初始化方法
        :param num_sides: 骰子的面数
        """
        self.num_sides = num_sides
    def roll(self):
        """
        掷骰子,Return random integer in range [a, b], including both end points.
        :return:
        """
        return randint(1, self.num_sides)
def draw(data_dict: dict):
    """
    绘图
    :param data_dict:
    :return:
    """
    hist = pygal.Bar()
    hist.title = "投掷两个1000次6面筛子的结果统计"
    hist.x_labels = data_dict.keys()
    hist.x_title = "两个骰子的点数之和"
    hist.y_title = "点数对应的次数"
    hist.add('两个6面骰子', data_dict.values())
    # 导出问文件,扩展名必须为`.svg`
    hist.render_to_file('die_visual.svg')
die1 = Die()
die2 = Die()
result_list = []
# 掷骰子并保存结果
for i in range(1000):
    result_list.append(die1.roll() + die2.roll())
# 点数:出现次数
point_count_dict = {}
# 分析每个点数出现的次数
for i in range(2, 2 * die1.num_sides + 1):
    point_count_dict[i] = result_list.count(i)
# 绘图
draw(point_count_dict)


  • 结果
  • 出现点数之和为7的概率永远是最高的,因为7的组合方式最多~


image.png

相关文章
|
2月前
|
存储 数据采集 监控
Python定时爬取新闻网站头条:从零到一的自动化实践
在信息爆炸时代,本文教你用Python定时爬取腾讯新闻头条,实现自动化监控。涵盖请求、解析、存储、去重、代理及异常通知,助你构建高效新闻采集系统,适用于金融、电商、媒体等场景。(238字)
333 2
|
3月前
|
人工智能 Shell Python
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
234 0
|
3月前
|
异构计算 Python
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
347 1
|
3月前
|
API 语音技术 开发者
Python 项目打包,并上传到 PyPI,分享项目
本文介绍了如何使用 Poetry 打包并发布一个 Python 项目至 PyPI。内容包括:项目创建、配置 `pyproject.toml` 文件、构建软件包、上传至 PyPI、安装与使用。通过实例 iGTTS 展示了从开发到发布的完整流程,帮助开发者快速分享自己的 Python 工具。
机器学习/深度学习 算法 自动驾驶
567 0
|
3月前
|
存储 人工智能 算法
Python实现简易成语接龙小游戏:从零开始的趣味编程实践
本项目将中国传统文化与编程思维相结合,通过Python实现成语接龙游戏,涵盖数据结构、算法设计与简单AI逻辑,帮助学习者在趣味实践中掌握编程技能。
354 0
|
3月前
|
大数据 数据处理 数据安全/隐私保护
Python3 迭代器与生成器详解:从入门到实践
简介:本文深入解析Python中处理数据序列的利器——迭代器与生成器。通过通俗语言与实战案例,讲解其核心原理、自定义实现及大数据处理中的高效应用。
164 0
|
4月前
|
数据采集 Web App开发 JSON
Python爬虫基本原理与HTTP协议详解:从入门到实践
本文介绍了Python爬虫的核心知识,涵盖HTTP协议基础、请求与响应流程、常用库(如requests、BeautifulSoup)、反爬应对策略及实战案例(如爬取豆瓣电影Top250),帮助读者系统掌握数据采集技能。
321 0
|
4月前
|
传感器 数据采集 监控
Python生成器与迭代器:从内存优化到协程调度的深度实践
简介:本文深入解析Python迭代器与生成器的原理及应用,涵盖内存优化技巧、底层协议实现、生成器通信机制及异步编程场景。通过实例讲解如何高效处理大文件、构建数据流水线,并对比不同迭代方式的性能特点,助你编写低内存、高效率的Python代码。
221 0
|
4月前
|
人工智能 自然语言处理 安全
Python构建MCP服务器:从工具封装到AI集成的全流程实践
MCP协议为AI提供标准化工具调用接口,助力模型高效操作现实世界。
831 1

推荐镜像

更多