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 26 Python
python实现随机漫步算法
Aug 27 Python
在Python中给Nan值更改为0的方法
Oct 30 Python
django之状态保持-使用redis存储session的例子
Jul 28 Python
python 画3维轨迹图并进行比较的实例
Dec 06 Python
torch 中各种图像格式转换的实现方法
Dec 26 Python
Python抓包程序mitmproxy安装和使用过程图解
Mar 02 Python
详解Flask前后端分离项目案例
Jul 24 Python
Python文件名匹配与文件复制的实现
Dec 11 Python
python中四舍五入的正确打开方式
Jan 18 Python
详解Pymongo常用查询方法总结
Jan 29 Python
图神经网络GNN算法
May 11 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 magic_quotes_gpc的使用方法详解
2013/06/24 PHP
JS 自动安装exe程序
2008/11/30 Javascript
JavaScript 动态改变图片大小
2009/06/11 Javascript
javascript 当前日期转化为中文的实现代码
2010/05/13 Javascript
整理AngularJS框架使用过程当中的一些性能优化要点
2016/03/05 Javascript
JQuery点击事件回到页面顶部效果的实现代码
2016/05/24 Javascript
浅谈js函数中的实例对象、类对象、局部变量(局部函数)
2016/11/20 Javascript
微信小程序 九宫格实例代码
2017/01/21 Javascript
js for循环倒序输出数组元素的实例
2017/03/01 Javascript
js实现一键复制功能
2017/03/16 Javascript
对mac下nodejs 更新到最新版本的最新方法(推荐)
2018/05/17 NodeJs
vue vue-Router默认hash模式修改为history需要做的修改详解
2018/09/13 Javascript
详解webpack4之splitchunksPlugin代码包分拆
2018/12/04 Javascript
js中对象和面向对象与Json介绍
2019/01/21 Javascript
vue.js+elementUI实现点击左右箭头切换头像功能(类似轮播图效果)
2019/09/05 Javascript
python虚拟环境virtualenv的安装与使用
2017/09/21 Python
python 执行shell命令并将结果保存的实例
2018/05/11 Python
Flask核心机制之上下文源码剖析
2018/12/25 Python
python爬虫基础教程:requests库(二)代码实例
2019/04/09 Python
Python OpenCV利用笔记本摄像头实现人脸检测
2020/08/20 Python
使用turtle绘制五角星、分形树
2019/10/06 Python
将python2.7添加进64位系统的注册表方式
2019/11/20 Python
彻底解决pip下载pytorch慢的问题方法
2021/03/01 Python
html5新特性与用法大全
2018/09/13 HTML / CSS
Scholastic父母商店:儿童书籍
2017/01/01 全球购物
JD Sports瑞典:英国领先的运动时尚商店
2018/01/28 全球购物
Fox Racing英国官网:越野摩托车和山地自行车服装
2020/02/26 全球购物
JAVA高级程序员面试题
2013/09/06 面试题
计算机专业自荐信
2014/05/24 职场文书
学校消防安全责任书
2014/07/23 职场文书
新教师教学工作总结
2015/08/14 职场文书
2016幼儿园教师年度考核评语
2015/12/01 职场文书
Prometheus 监控MySQL使用grafana展示
2021/08/30 MySQL
《原神》新角色演示“神里绫人:林隐泓洄” 宠妹狂魔
2022/04/03 其他游戏
《杜鹃的婚约》OP主题曲「凸凹」无字幕影像公开
2022/04/08 日漫
Java代码规范与质量检测插件SonarLint的使用
2022/08/05 Java/Android