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中查找excel某一列的重复数据 剔除之后打印
Feb 10 Python
Python中自定义函数的教程
Apr 27 Python
python中while循环语句用法简单实例
May 07 Python
实例讲解Python中函数的调用与定义
Mar 14 Python
Python提取网页中超链接的方法
Sep 18 Python
Python中字典和集合学习小结
Jul 07 Python
Python搜索引擎实现原理和方法
Nov 27 Python
Python实现读取txt文件并画三维图简单代码示例
Dec 09 Python
利用python如何处理nc数据详解
May 23 Python
python中的colorlog库使用详解
Jul 05 Python
在django中图片上传的格式校验及大小方法
Jul 28 Python
完美解决python针对hdfs上传和下载的问题
Jun 05 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
优化使用mysql存储session的php代码
2008/01/10 PHP
DHTML 中的绝对定位
2006/11/26 Javascript
百度地图api应用标注地理位置信息(js版)
2013/02/01 Javascript
JS控件ASP.NET的treeview控件全选或者取消(示例代码)
2013/12/16 Javascript
jQuery扁平化风格下拉框美化插件FancySelect使用指南
2015/02/10 Javascript
js简单实现Select互换数据的方法
2015/08/17 Javascript
MVC Ajax Helper或Jquery异步加载部分视图
2015/11/29 Javascript
vue日期组件 支持vue1.0和2.0
2017/01/09 Javascript
el表达式 写入bootstrap表格数据页面的实例代码
2017/01/11 Javascript
jQuery插件HighCharts绘制2D饼图效果示例【附demo源码下载】
2017/03/21 jQuery
使用Browserify来实现CommonJS的浏览器加载方法
2017/05/14 Javascript
javascript实现二叉树遍历的代码
2017/06/08 Javascript
Vue2.0 组件传值通讯的示例代码
2017/08/01 Javascript
JS实现前端缓存的方法
2017/09/21 Javascript
全面分析JavaScript 继承
2019/05/30 Javascript
Vue-cli3.x + axios 跨域方案踩坑指北
2019/07/04 Javascript
详解javascript中var与ES6规范中let、const区别与用法
2020/01/11 Javascript
Vue 集成 PDF.js 实现 PDF 预览和添加水印的步骤
2021/01/22 Vue.js
python使用PythonMagick将jpg图片转换成ico图片的方法
2015/03/26 Python
Python3中多线程编程的队列运作示例
2015/04/16 Python
python3使用urllib模块制作网络爬虫
2016/04/08 Python
django创建自定义模板处理器的实例详解
2017/08/14 Python
基于Python闭包及其作用域详解
2017/08/28 Python
详解Python中 sys.argv[]的用法简明解释
2017/12/20 Python
Python cookbook(数据结构与算法)将多个映射合并为单个映射的方法
2018/04/19 Python
python 3.6.5 安装配置方法图文教程
2018/09/18 Python
python 返回一个列表中第二大的数方法
2019/07/09 Python
Django RBAC权限管理设计过程详解
2019/08/06 Python
PyCharm汉化安装及永久激活详细教程(靠谱)
2020/01/16 Python
Python安装并操作redis实现流程详解
2020/10/13 Python
android面试问题与答案
2016/12/27 面试题
介绍下Java中==和equals的区别
2013/09/01 面试题
安全生产检查通报
2014/01/29 职场文书
七一建党节慰问信
2015/02/14 职场文书
2015年为民办实事工作总结
2015/05/26 职场文书
Redis过期数据是否会被立马删除
2022/07/23 Redis