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让图片按照exif信息里的创建时间进行排序的方法
Mar 16 Python
Python自动生产表情包
Mar 17 Python
ubuntu安装sublime3并配置python3环境的方法
Mar 15 Python
基于scrapy的redis安装和配置方法
Jun 13 Python
django如何实现视图重定向
Jul 24 Python
Python3 tkinter 实现文件读取及保存功能
Sep 12 Python
Python利用逻辑回归模型解决MNIST手写数字识别问题详解
Jan 14 Python
python利用Excel读取和存储测试数据完成接口自动化教程
Apr 30 Python
Python操作Elasticsearch处理timeout超时
Jul 17 Python
如何使用Pytorch搭建模型
Oct 26 Python
DjangoRestFramework 使用 simpleJWT 登陆认证完整记录
Jun 22 Python
python神经网络学习 使用Keras进行简单分类
May 04 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 设计模式之 工厂模式
2008/12/19 PHP
微信公众平台开发之配置与请求
2015/08/26 PHP
详解PHP的Yii框架的运行机制及其路由功能
2016/03/17 PHP
详谈配置phpstorm完美支持Codeigniter(CI)代码自动完成(代码提示)
2017/04/07 PHP
PHP反射学习入门示例
2019/06/14 PHP
php实现的生成排列算法示例
2019/07/25 PHP
Jquery 弹出层插件实现代码
2009/10/24 Javascript
基于jquery的获取浏览器窗口大小的代码
2011/03/28 Javascript
jquery submit()不能提交表单的解决方法
2017/04/24 jQuery
Node.js服务器开启Gzip压缩教程
2017/08/11 Javascript
详解从新建vue项目到引入组件Element的方法
2017/08/29 Javascript
微信小程序支付之c#后台实现方法
2017/10/19 Javascript
利用jQuery实现简单的拖曳效果实例代码
2017/10/20 jQuery
解决vue处理axios post请求传参的问题
2018/03/05 Javascript
vue router带参数页面刷新或回退参数消失的解决方法
2019/02/27 Javascript
javascript头像上传代码实例
2019/09/28 Javascript
在Vue里如何把网页的数据导出到Excel的方法
2020/09/30 Javascript
[03:49]辉夜杯现场龙骑士COSER秀情商“我喜欢芬队!”
2015/12/27 DOTA
python爬取网站数据保存使用的方法
2013/11/20 Python
处理Python中的URLError异常的方法
2015/04/30 Python
OpenCV-Python实现轮廓检测实例分析
2018/01/05 Python
Python求两个圆的交点坐标或三个圆的交点坐标方法
2018/11/07 Python
python requests post多层字典的方法
2018/12/27 Python
python射线法判断一个点在图形区域内外
2019/06/28 Python
浅析python表达式4+0.5值的数据类型
2020/02/26 Python
如何通过python实现IOU计算代码实例
2020/11/02 Python
Css3新特性应用之形状总结
2016/12/08 HTML / CSS
css3翻牌翻数字的示例代码
2020/02/07 HTML / CSS
HTML5仿手机微信聊天界面
2016/03/18 HTML / CSS
HTML5新增的8类INPUT输入类型介绍
2015/07/06 HTML / CSS
欧洲最大的笔和书写专家:The Pen Shop
2017/03/19 全球购物
什么是动态端口(Dynamic Ports)?动态端口的范围是多少?
2014/12/12 面试题
英语老师推荐信
2014/02/26 职场文书
手机银行营销方案
2014/03/14 职场文书
十佳护士先进事迹
2014/05/08 职场文书
2014县政府领导班子对照检查材料思想汇报
2014/09/25 职场文书