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使用爬虫猜密码
Feb 19 Python
使用sklearn进行对数据标准化、归一化以及将数据还原的方法
Jul 11 Python
python从入门到精通 windows安装python图文教程
May 18 Python
python实现统计文本中单词出现的频率详解
May 20 Python
python selenium操作cookie的实现
Mar 18 Python
python2.7使用scapy发送syn实例
May 05 Python
Python不支持 i ++ 语法的原因解析
Jul 22 Python
Python限制内存和CPU使用量的方法(Unix系统适用)
Aug 04 Python
如何利用Python给自己的头像加一个小国旗(小月饼)
Oct 02 Python
Python特殊属性property原理及使用方法解析
Oct 09 Python
python UIAutomator2使用超详细教程
Feb 19 Python
Pycharm连接远程服务器并远程调试的全过程
Jun 24 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 UTF8 文件的签名问题
2009/10/30 PHP
基于jquery的3d效果实现代码
2011/03/23 Javascript
javascript修改表格背景色实例代码分享
2013/12/10 Javascript
jquery实现checkbox 全选/全不选的通用写法
2014/02/22 Javascript
jquery实现背景墙聚光灯效果示例分享
2014/03/02 Javascript
Node.js 异步编程之 Callback介绍(一)
2015/03/30 Javascript
AngularJS基础 ng-keypress 指令简单示例
2016/08/02 Javascript
AngularJS基础 ng-keypress 指令简单示例
2016/08/02 Javascript
深入理解javascript函数参数与闭包
2016/12/12 Javascript
详解Vue监听数据变化原理
2017/03/08 Javascript
Bootstrap栅格系统的使用详解
2017/10/30 Javascript
解决angularjs WdatePicker ng-model的问题
2018/09/13 Javascript
使用Three.js实现太阳系八大行星的自转公转示例代码
2019/04/09 Javascript
JS常见错误(Error)及处理方案详解
2020/07/02 Javascript
python获取豆瓣电影简介代码分享
2014/01/16 Python
在Python中使用Neo4j数据库的教程
2015/04/16 Python
python常见的格式化输出小结
2016/12/15 Python
python中如何使用正则表达式的集合字符示例
2017/10/09 Python
Python比较2个时间大小的实现方法
2018/04/10 Python
python 匹配url中是否存在IP地址的方法
2018/06/04 Python
利用pyinstaller打包exe文件的基本教程
2019/05/02 Python
pymysql 开启调试模式的实现
2019/09/24 Python
Tensorflow的梯度异步更新示例
2020/01/23 Python
Python Handler处理器和自定义Opener原理详解
2020/03/05 Python
Python3标准库之threading进程中管理并发操作方法
2020/03/30 Python
Python如何将字符串转换为日期
2020/07/31 Python
Bluebella法国官网:英国性感内衣品牌
2019/05/03 全球购物
董事长秘书职责
2014/01/31 职场文书
2014厂务公开实施方案
2014/02/17 职场文书
《独坐敬亭山》教学反思
2014/04/08 职场文书
2015年保育员个人工作总结
2015/05/13 职场文书
党小组考察意见
2015/06/02 职场文书
关于python pygame游戏进行声音添加的技巧
2021/10/24 Python
Python if else条件语句形式详解
2022/03/24 Python
sentinel支持的redis高可用集群配置详解
2022/04/01 Redis
使用Cargo工具高效创建Rust项目
2022/08/14 Javascript