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检索特定内容的文本文件实例
Jun 05 Python
Python3编码问题 Unicode utf-8 bytes互转方法
Oct 26 Python
win7 x64系统中安装Scrapy的方法
Nov 18 Python
python读取文件名并改名字的实例
Jan 07 Python
Python从文件中读取数据的方法讲解
Feb 14 Python
django模板加载静态文件的方法步骤
Mar 01 Python
Django框架视图介绍与使用详解
Jul 18 Python
Python命令行click参数用法解析
Dec 19 Python
Python基础教程(一)——Windows搭建开发Python开发环境
Jul 20 Python
python 模拟登录B站的示例代码
Dec 15 Python
pandas中DataFrame数据合并连接(merge、join、concat)
May 30 Python
Python数据分析之绘图和可视化详解
Jun 02 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
可快速识别放射性物质-国外大神教你diy一个开放式辐射探测器
2020/03/12 无线电
PHP的类 功能齐全的发送邮件类
2006/10/09 PHP
IStream与TStream之间的相互转换
2008/08/01 PHP
PHP 数组实例说明
2008/08/18 PHP
PHP MemCached 高级缓存应用代码
2010/08/05 PHP
详解PHP内置访问资源的超时时间 time_out file_get_contents read_file
2013/06/03 PHP
php上传文件并存储到mysql数据库的方法
2015/03/16 PHP
基于Jquery的实现回车键Enter切换焦点
2010/09/14 Javascript
JS 屏蔽按键效果与改变按键效果的示例代码
2013/12/24 Javascript
Javascript自定义函数判断网站访问类型是PC还是移动终端
2014/01/10 Javascript
深入理解javascript中的立即执行函数(function(){…})()
2014/06/12 Javascript
node.js中的buffer.toJSON方法使用说明
2014/12/14 Javascript
JS或jQuery获取ASP.NET服务器控件ID的方法
2015/06/08 Javascript
jquery实现经典的淡入淡出选项卡效果代码
2015/09/22 Javascript
jQuery-1.9.1源码分析系列(十)事件系统之事件包装
2015/11/20 Javascript
Nodejs初级阶段之express
2015/11/23 NodeJs
jquery ajax分页插件的简单实现
2016/01/27 Javascript
AngularJS延迟加载html template
2016/07/27 Javascript
点击页面任何位置隐藏div的实现方法
2016/09/05 Javascript
微信小程序 数据绑定及运算的简单实例
2017/09/20 Javascript
webpack 单独打包指定JS文件的方法
2018/02/22 Javascript
JQuery样式操作、click事件以及索引值-选项卡应用示例
2019/05/14 jQuery
vue 解决mintui弹窗弹起来,底部页面滚动bug问题
2020/11/12 Javascript
python3 实现的人人影视网站自动签到
2016/06/19 Python
你应该知道的python列表去重方法
2017/01/17 Python
关于 Python opencv 使用中的 ValueError: too many values to unpack
2019/06/28 Python
在linux下实现 python 监控usb设备信号
2019/07/03 Python
pandas实现to_sql将DataFrame保存到数据库中
2019/07/03 Python
python实现截取屏幕保存文件,删除N天前截图的例子
2019/08/27 Python
Python应用实现处理excel数据过程解析
2020/06/19 Python
python PyAUtoGUI库实现自动化控制鼠标键盘
2020/09/09 Python
使用css创建三角形 使用CSS3创建3d四面体原理及代码(html5实践)
2013/01/06 HTML / CSS
浅谈HTML5 FileReader分布读取文件以及其方法简介
2017/11/09 HTML / CSS
Keds官方网站:购买帆布运动鞋和经典皮鞋
2016/11/12 全球购物
毕业学生推荐信
2013/12/01 职场文书
2015年店长工作总结范文
2015/04/08 职场文书