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 07 Python
几行Python代码爬取3000+上市公司的信息
Jan 24 Python
Python实现E-Mail收集插件实例教程
Feb 06 Python
Django model select的多种用法详解
Jul 16 Python
django框架面向对象ORM模型继承用法实例分析
Jul 29 Python
Django如何实现上传图片功能
Aug 16 Python
Django框架model模型对象验证实现方法分析
Oct 02 Python
Python使用psutil获取进程信息的例子
Dec 17 Python
python实现跨excel sheet复制代码实例
Mar 03 Python
使用Keras预训练好的模型进行目标类别预测详解
Jun 27 Python
python利用递归方法实现求集合的幂集
Sep 07 Python
matplotlib部件之矩形选区(RectangleSelector)的实现
Feb 01 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获取当前页面完整URL的实现代码
2013/06/10 PHP
Ubuntu中搭建Nginx、PHP环境最简单的方法
2015/03/05 PHP
JavaScript 验证浏览器是否支持javascript的方法小结
2009/05/17 Javascript
IE8中使用javascript动态加载CSS的解决方法
2014/06/17 Javascript
Firefox下无法正常显示年份的解决方法
2014/09/04 Javascript
JS数组(Array)处理函数整理
2014/12/07 Javascript
javascript无刷新评论实现方法
2015/05/13 Javascript
javascript判断复选框是否选中的方法
2015/10/16 Javascript
EditPlus中的正则表达式 实战(2)
2016/12/15 Javascript
AngularJS框架的ng-app指令与自动加载实现方法分析
2017/01/04 Javascript
详解使用JS如何制作简单的ASCII图与单极图
2017/03/31 Javascript
浅析为什么a="abc" 不等于 a=new String("abc")
2017/10/25 Javascript
javascript实现获取一个日期段内每天不同的价格(计算入住总价格)
2018/02/05 Javascript
Node对CommonJS的模块规范
2019/11/06 Javascript
vue渲染方式render和template的区别
2020/06/05 Javascript
Python3实现发送QQ邮件功能(附件)
2020/12/23 Python
Python实现JSON反序列化类对象的示例
2018/01/31 Python
Python实现定时精度可调节的定时器
2018/04/15 Python
深入浅析Python2.x和3.x版本的主要区别
2018/11/30 Python
python文档字符串(函数使用说明)使用详解
2019/07/30 Python
Django获取应用下的所有models的例子
2019/08/30 Python
python实现二分类的卡方分箱示例
2019/11/22 Python
python deque模块简单使用代码实例
2020/03/12 Python
美国著名手表网站:Timepiece
2017/11/15 全球购物
获取邓白氏信用报告:Dun & Bradstreet
2019/01/22 全球购物
什么是接口(Interface)?
2013/02/01 面试题
国际商务专业职业生涯规划书范文
2014/01/17 职场文书
同学聚会老师邀请函
2014/01/28 职场文书
迎新晚会主持词
2014/03/24 职场文书
共筑中国梦演讲稿
2014/04/23 职场文书
停车场管理协议书范本
2014/10/08 职场文书
党的群众路线教育实践活动教师自我剖析材料
2014/10/09 职场文书
毕业设计致谢语
2015/05/14 职场文书
格林童话读书笔记
2015/06/30 职场文书
2015年信息化建设工作总结
2015/07/23 职场文书
低版本Druid连接池+MySQL驱动8.0导致线程阻塞、性能受限
2021/07/01 MySQL