【python入门项目】在 Python 中创建条形图追赶动画(2)

简介: 【python入门项目】在 Python 中创建条形图追赶动画

Python 中的散点图动画:


在这个例子中,我们将使用随机函数在 python 中动画散点图。我们将遍历animation_func并在迭代时绘制 x 和 y 轴的随机值。

from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import random
import numpy as np
x = []
y = []
colors = []
fig = plt.figure(figsize=(7,5))
def animation_func(i):
  x.append(random.randint(0,100))
  y.append(random.randint(0,100))
  colors.append(np.random.rand(1))
  area = random.randint(0,30) * random.randint(0,30)
  plt.xlim(0,100)
  plt.ylim(0,100)
  plt.scatter(x, y, c = colors, s = area, alpha = 0.5)
animation = FuncAnimation(fig, animation_func,
            interval = 100)
plt.show()


输出:

f028be7bdc104933bd770b81803d7c14.gif

🛹 条形图追赶的水平移动:


在这里,我们将使用城市数据集中的最高人口绘制条形图竞赛。

不同的城市会有不同的条形图,条形图追赶将从 1990 年到 2018 年迭代。

我从人口最多的数据集中选择了最高城市的国家。

需要用到的数据集可以从这里下载:city_populations


Python

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.animation import FuncAnimation
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  
df = pd.read_csv('city_populations.csv',
                 usecols=['name', 'group', 'year', 'value'])
colors = dict(zip(['India','Europe','Asia',
                   'Latin America','Middle East',
                   'North America','Africa'],
                    ['#adb0ff', '#ffb3ff', '#90d595',
                     '#e48381', '#aafbff', '#f7bb5f', 
                     '#eafb50']))
group_lk = df.set_index('name')['group'].to_dict()
def draw_barchart(year):
    dff = df[df['year'].eq(year)].sort_values(by='value',
                                              ascending=True).tail(10)
    ax.clear()
    ax.barh(dff['name'], dff['value'],
            color=[colors[group_lk[x]] for x in dff['name']])
    dx = dff['value'].max() / 200
    for i, (value, name) in enumerate(zip(dff['value'],
                                          dff['name'])):
        ax.text(value-dx, i,     name,           
                size=14, weight=600,
                ha='right', va='bottom')
        ax.text(value-dx, i-.25, group_lk[name],
                size=10, color='#444444', 
                ha='right', va='baseline')
        ax.text(value+dx, i,     f'{value:,.0f}', 
                size=14, ha='left',  va='center')
    ax.text(1, 0.4, year, transform=ax.transAxes, 
            color='#777777', size=46, ha='right',
            weight=800)
    ax.text(0, 1.06, 'Population (thousands)',
            transform=ax.transAxes, size=12,
            color='#777777')
    ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
    ax.xaxis.set_ticks_position('top')
    ax.tick_params(axis='x', colors='#777777', labelsize=12)
    ax.set_yticks([])
    ax.margins(0, 0.01)
    ax.grid(which='major', axis='x', linestyle='-')
    ax.set_axisbelow(True)
    ax.text(0, 1.12, '从 1500 年到 2018 年世界上人口最多的城市',
            transform=ax.transAxes, size=24, weight=600, ha='left')
    ax.text(1, 0, 'by haiyong.site | 海拥', 
            transform=ax.transAxes, ha='right', color='#777777', 
            bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
    plt.box(False)
    plt.show()
fig, ax = plt.subplots(figsize=(15, 8))
animator = FuncAnimation(fig, draw_barchart, 
                         frames = range(1990, 2019))
plt.show()


输出:

0d4f48631a9c4c7583044a853f6e5793.gif

目录
相关文章
|
2月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
302 7
|
3月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
334 1
|
2月前
|
Cloud Native 算法 API
Python API接口实战指南:从入门到精通
🌟蒋星熠Jaxonic,技术宇宙的星际旅人。深耕API开发,以Python为舟,探索RESTful、GraphQL等接口奥秘。擅长requests、aiohttp实战,专注性能优化与架构设计,用代码连接万物,谱写极客诗篇。
Python API接口实战指南:从入门到精通
|
3月前
|
异构计算 Python
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
325 1
|
2月前
|
存储 Java 调度
Python定时任务实战:APScheduler从入门到精通
APScheduler是Python强大的定时任务框架,通过触发器、执行器、任务存储和调度器四大组件,灵活实现各类周期性任务。支持内存、数据库、Redis等持久化存储,适用于Web集成、数据抓取、邮件发送等场景,解决传统sleep循环的诸多缺陷,助力构建稳定可靠的自动化系统。(238字)
493 1
|
3月前
|
调度 数据库 Python
Python异步编程入门:asyncio让并发变得更简单
Python异步编程入门:asyncio让并发变得更简单
194 5
|
3月前
|
API 语音技术 开发者
Python 项目打包,并上传到 PyPI,分享项目
本文介绍了如何使用 Poetry 打包并发布一个 Python 项目至 PyPI。内容包括:项目创建、配置 `pyproject.toml` 文件、构建软件包、上传至 PyPI、安装与使用。通过实例 iGTTS 展示了从开发到发布的完整流程,帮助开发者快速分享自己的 Python 工具。
|
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项目依赖冲突的解决方案-优雅草优雅草卓伊凡
225 0
|
3月前
|
数据采集 存储 XML
Python爬虫入门(1)
在互联网时代,数据成为宝贵资源,Python凭借简洁语法和丰富库支持,成为编写网络爬虫的首选。本文介绍Python爬虫基础,涵盖请求发送、内容解析、数据存储等核心环节,并提供环境配置及实战示例,助你快速入门并掌握数据抓取技巧。
|
3月前
|
大数据 数据处理 数据安全/隐私保护
Python3 迭代器与生成器详解:从入门到实践
简介:本文深入解析Python中处理数据序列的利器——迭代器与生成器。通过通俗语言与实战案例,讲解其核心原理、自定义实现及大数据处理中的高效应用。
157 0

推荐镜像

更多