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比较两个列表大小的方法
Jul 11 Python
Python简单实现控制电脑的方法
Jan 22 Python
python实现淘宝秒杀聚划算抢购自动提醒源码
Jun 23 Python
深入理解Django自定义信号(signals)
Oct 15 Python
在unittest中使用 logging 模块记录测试数据的方法
Nov 30 Python
对python中数据集划分函数StratifiedShuffleSplit的使用详解
Dec 11 Python
Django项目中使用JWT的实现代码
Nov 04 Python
wxPython实现整点报时
Nov 18 Python
Python pip install如何修改默认下载路径
Apr 29 Python
解决python运行效率不高的问题
Jul 20 Python
python爬取网易云音乐热歌榜实例代码
Aug 07 Python
简单且有用的Python数据分析和机器学习代码
Jul 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
php抓取页面的几种方法详解
2013/06/17 PHP
解析PHP中常见的mongodb查询操作
2013/06/20 PHP
php实现mysql备份恢复分卷处理的方法
2014/12/26 PHP
PHP验证信用卡卡号是否正确函数
2015/05/27 PHP
PHP基于Redis消息队列实现发布微博的方法
2017/05/03 PHP
利用Ext Js生成动态树实例代码
2008/09/08 Javascript
浅谈Javascript事件模拟
2012/06/27 Javascript
jquery 按钮状态效果 正常、移上、按下
2013/08/12 Javascript
js的参数有长度限制吗?发现不能超过2083个字符
2014/04/20 Javascript
JavaScript Math.ceil 方法(对数值向上取整)
2015/01/09 Javascript
js实现接收表单的值并将值拼在表单action后面的方法
2015/11/23 Javascript
AngularJS之依赖注入模拟实现
2016/08/19 Javascript
AngularJs  unit-testing(单元测试)详解
2016/09/02 Javascript
jQuery删除当前节点元素
2016/12/07 Javascript
AngularJS使用ng-class动态增减class样式的方法示例
2017/05/18 Javascript
requirejs按需加载angularjs文件实例
2017/06/08 Javascript
nodejs express配置自签名https服务器的方法
2018/05/22 NodeJs
Element-ui之ElScrollBar组件滚动条的使用方法
2018/09/14 Javascript
vue过滤器用法实例分析
2019/03/15 Javascript
Vue 页面权限控制和登陆验证功能的实例代码
2019/06/20 Javascript
vue中实现点击变成全屏的多种方法
2020/09/27 Javascript
vue打包通过image-webpack-loader插件对图片压缩优化操作
2020/11/12 Javascript
javascript实现左右缓动动画函数
2020/11/25 Javascript
[43:51]2018DOTA2亚洲邀请赛3月30日 小组赛B组 EG VS Secret
2018/03/31 DOTA
举例简单讲解Python中的数据存储模块shelve的用法
2016/03/03 Python
Python实现嵌套列表及字典并按某一元素去重复功能示例
2017/11/30 Python
Win10下用Anaconda安装TensorFlow(图文教程)
2020/06/18 Python
基于CSS3实现的黑色个性导航菜单效果
2015/09/14 HTML / CSS
Johnson Fitness澳大利亚:高级健身器材
2021/03/16 全球购物
介绍一下Make? 为什么使用make
2013/12/08 面试题
医学类个人求职信范文
2014/02/05 职场文书
电厂职工自我鉴定
2014/02/20 职场文书
2014乡镇干部对照检查材料思想汇报
2014/09/26 职场文书
优秀护士事迹材料
2014/12/25 职场文书
安全生产先进个人总结
2015/02/15 职场文书
试用期转正工作总结2015
2015/05/28 职场文书