Python实现Matplotlib,Seaborn动态数据图


Posted in Python onMay 06, 2022

Matplotlib

效果图如下

Python实现Matplotlib,Seaborn动态数据图

主要使用matplotlib.animation.FuncAnimation,上核心代码,

# 定义静态绘图函数
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,
            '单位 (每1000)',
            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')
    
    plt.box(False)


# 调用matplotlib.animation.FuncAnimation让静态图动起来
animator = animation.FuncAnimation(fig,
                                   draw_barchart,
                                   frames=range(1968, 2019))
# Jupyter Notebook里展示动图animation
HTML(animator.to_jshtml())

在绘图数据部分改自己的数据既可为所欲为的使用了~

Seaborn

效果图如下

Python实现Matplotlib,Seaborn动态数据图

代码

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import seaborn as sns
import numpy as np
import palettable


def get_data(i=0):
    x, y = np.random.normal(loc=i, scale=3, size=(2, 260))
    return x, y
x, y = get_data()


g = sns.JointGrid(x=x, y=y, size=4)
g.fig.set_size_inches(10, 8)
lim = (-10, 10)


def prep_axes(g, xlim, ylim):
    g.ax_joint.clear()
    g.ax_joint.set_xlim(xlim)
    g.ax_joint.set_ylim(ylim)
    g.ax_marg_x.clear()
    g.ax_marg_x.set_xlim(xlim)
    g.ax_marg_y.clear()
    g.ax_marg_y.set_ylim(ylim)
    plt.setp(g.ax_marg_x.get_xticklabels(), visible=False)
    plt.setp(g.ax_marg_y.get_yticklabels(), visible=False)
    plt.setp(g.ax_marg_x.yaxis.get_majorticklines(), visible=False)
    plt.setp(g.ax_marg_x.yaxis.get_minorticklines(), visible=False)
    plt.setp(g.ax_marg_y.xaxis.get_majorticklines(), visible=False)
    plt.setp(g.ax_marg_y.xaxis.get_minorticklines(), visible=False)
    plt.setp(g.ax_marg_x.get_yticklabels(), visible=False)
    plt.setp(g.ax_marg_y.get_xticklabels(), visible=False)


def animate(i):
    g.x, g.y = get_data(i)
    prep_axes(g, lim, lim)
    g.plot_joint(sns.kdeplot,
                 cmap='Paired')
    g.plot_marginals(sns.kdeplot, color='blue', shade=True)


frames = np.sin(np.linspace(0, 2 * np.pi, 17)) * 5
ani = matplotlib.animation.FuncAnimation(g.fig,
                                         animate,
                                         frames=frames,
                                         repeat=True)
HTML(ani.to_jshtml())

和Matplotlib代码类似,不过多解释。

到此这篇关于Python实现Matplotlib,Seaborn动态数据图的文章就介绍到这了!


Tags in this post...

Python 相关文章推荐
Python中使用md5sum检查目录中相同文件代码分享
Feb 02 Python
python实现定时同步本机与北京时间的方法
Mar 24 Python
python中黄金分割法实现方法
May 06 Python
Python简单操作sqlite3的方法示例
Mar 22 Python
python中nan与inf转为特定数字方法示例
May 11 Python
Python实现扩展内置类型的方法分析
Oct 16 Python
pycharm远程开发项目的实现步骤
Jan 20 Python
django框架模板语言使用方法详解
Jul 18 Python
Django 实现外键去除自动添加的后缀‘_id’
Nov 15 Python
在Python中使用K-Means聚类和PCA主成分分析进行图像压缩
Apr 10 Python
通过实例解析Python文件操作实现步骤
Sep 21 Python
Django-simple-captcha验证码包使用方法详解
Nov 28 Python
PYTHON InceptionV3模型的复现详解
代码复现python目标检测yolo3详解预测
讲解Python实例练习逆序输出字符串
May 06 #Python
python turtle绘图
May 04 #Python
python blinker 信号库
May 04 #Python
python三子棋游戏
May 04 #Python
python神经网络 使用Keras构建RNN训练
May 04 #Python
You might like
PHP 输出缓存详解
2009/06/20 PHP
PHP防止注入攻击实例分析
2014/11/03 PHP
PHP请求远程地址设置超时时间的解决方法
2016/10/29 PHP
PHP简单实现模拟登陆功能示例
2017/09/15 PHP
PJ Blog修改-禁止复制的代码和方法
2006/10/25 Javascript
禁止js文件缓存的代码
2010/04/09 Javascript
使用js dom和jquery分别实现简单增删改
2014/09/11 Javascript
EasyUI,点击开启编辑框,并且编辑框获得焦点的方法
2015/03/01 Javascript
js计算德州扑克牌面值的方法
2015/03/04 Javascript
全面解析Bootstrap手风琴效果
2020/04/17 Javascript
jQuery判断浏览器并动态调整select宽度的方法
2016/03/02 Javascript
js拖拽的原型声明和用法总结
2016/04/04 Javascript
JavaScript学习笔记整理_关于表达式和语句
2016/09/19 Javascript
详解通过JSON数据使用VUE.JS
2017/05/26 Javascript
基于复选框demo(分享)
2017/09/27 Javascript
Three.js 再探 - 写一个微信跳一跳极简版游戏
2018/01/04 Javascript
webpack@v4升级踩坑(小结)
2018/10/08 Javascript
vue模块拖拽实现示例代码
2019/03/09 Javascript
nodejs中request库使用HTTPS代理的方法
2019/04/30 NodeJs
javascript实现贪吃蛇游戏(娱乐版)
2020/08/17 Javascript
Vue实现导航栏菜单
2020/08/19 Javascript
[06:16]第十四期-国士无双绝地翻盘之撼地神牛
2014/06/24 DOTA
[01:00:25]NB vs Secret 2018国际邀请赛小组赛BO1 B组加赛 8.19
2018/08/21 DOTA
[45:14]Optic vs VP 2018国际邀请赛淘汰赛BO3 第二场 8.24
2018/08/25 DOTA
在Python中使用HTMLParser解析HTML的教程
2015/04/29 Python
说一说Python logging
2016/04/15 Python
Python Paramiko模块的使用实际案例
2018/02/01 Python
使用HTML5中的contentEditable来将多行文本自动增高
2016/03/01 HTML / CSS
COSETTE官网:奢华,每天
2020/03/22 全球购物
模具数控专业自荐信
2014/01/27 职场文书
初中三好学生自我鉴定
2014/04/07 职场文书
部队反四风对照检查材料
2014/09/26 职场文书
工作失误检讨书(3篇)
2014/10/11 职场文书
选择比努力更重要?这是长期以来对“努力”的最大误解
2019/07/12 职场文书
Python time库的时间时钟处理
2021/05/02 Python
DSP接收机前端设想
2022/04/05 无线电