前面的作品可见:
数据可视化之美-动态图绘制(以Python为工具)

最近中了绘制动态图的毒,根本停不下来。


该篇博文是对上篇博文补充一些案例,并阐述一些绘图的优化。

绘动图之前准备工作

在运行程序之前,要确保 ImageMagic 安装好【下载链接】,然后就可以通过python的绘图工具包 matplotlib 保存 gif。
具体的安装教程可以见这篇博客【ImageMagic 安装教程】,准备工作完成了,然后就可以测试我们的案例了(包括上一篇博客的案例,以及这篇博客的案例)。见下。

Test1:简单的Matplotlib 画 GIF 动图

  • 图里的散点部分是不变的;变的是直线
  • 也可以在图中添加其他元素,如时间(设置这些元素的变化)
  • 我在这里优化了图的分辨率,使得GIF看起来更高清,见下面的代码串
anim.save('Test1_v1.gif', dpi=600, writer='imagemagick')
  • 绘图所有的代码串见下:
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# import seabornfig, ax = plt.subplots()
fig.set_tight_layout(True)#  询问图形在屏幕上的尺寸和DPI(每英寸点数)。
#  注意当我们把图形储存成一个文件时,我们需要再另外提供一个DPI值
print('fig size: {0} DPI, size in inches {1}'.format(fig.get_dpi(), fig.get_size_inches()))# 画出一个维持不变(不会被重画)的散点图和一开始的那条直线。
x = np.arange(0, 20, 0.1)
ax.scatter(x, x + np.random.normal(0, 3.0, len(x)))
line, = ax.plot(x, x - 5, 'r-', linewidth=2)def update(i):label = 'timestep {0}'.format(i)print(label)# 更新直线和x轴(用一个新的x轴的标签)。# 用元组(Tuple)的形式返回在这一帧要被重新绘图的物体line.set_ydata(x - 5 + i)# ax.set_xlabel(label)return line, axif __name__ == '__main__':# FuncAnimation 会在每一帧都调用“update” 函数。# 在这里设置一个10帧的动画,每帧之间间隔200毫秒anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)anim.save('Test1_v1.gif', dpi=600, writer='imagemagick')plt.show()

Test2:双摆问题

双摆是一个很经典的没有解析解的物理模型,如果对双摆公式感兴趣可见University of Sydney的物理专业的网页页面【双摆问题的介绍】:

底下这串代码也是通过更新数据的形式来更新动图里面的元素。见该部分

line.set_data(thisx, thisy)
time_text.set_text(time_template % (i*dt))

最终绘图所有的代码见下:

from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animationG = 9.8  # acceleration due to gravity, in m/s^2
L1 = 1.0  # length of pendulum 1 in m
L2 = 1.0  # length of pendulum 2 in m
M1 = 1.0  # mass of pendulum 1 in kg
M2 = 1.0  # mass of pendulum 2 in kgdef derivs(state, t):dydx = np.zeros_like(state)dydx[0] = state[1]del_ = state[2] - state[0]den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_)dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_) +M2*G*sin(state[2])*cos(del_) +M2*L2*state[3]*state[3]*sin(del_) -(M1 + M2)*G*sin(state[0]))/den1dydx[2] = state[3]den2 = (L2/L1)*den1dydx[3] = (-M2*L2*state[3]*state[3]*sin(del_)*cos(del_) +(M1 + M2)*G*sin(state[0])*cos(del_) -(M1 + M2)*L1*state[1]*state[1]*sin(del_) -(M1 + M2)*G*sin(state[2]))/den2return dydx# create a time array from 0..100 sampled at 0.05 second steps
dt = 0.05
t = np.arange(0.0, 20, dt)# th1 and th2 are the initial angles (degrees)
# w10 and w20 are the initial angular velocities (degrees per second)
th1 = 120.0
w1 = 0.0
th2 = -10.0
w2 = 0.0# initial state
state = np.radians([th1, w1, th2, w2])# integrate your ODE using scipy.integrate.
y = integrate.odeint(derivs, state, t)x1 = L1*sin(y[:, 0])
y1 = -L1*cos(y[:, 0])x2 = L2*sin(y[:, 2]) + x1
y2 = -L2*cos(y[:, 2]) + y1fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2))
ax.set_aspect('equal')
ax.grid()line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)def init():line.set_data([], [])time_text.set_text('')return line, time_textdef animate(i):thisx = [0, x1[i], x2[i]]thisy = [0, y1[i], y2[i]]line.set_data(thisx, thisy)time_text.set_text(time_template % (i*dt))return line, time_textani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)),interval=25, blit=True, init_func=init)ani.save("dp-test2.gif", writer="imagemagick")
plt.show()

Test3:一次性更新多个对象

  • 在这里也优化调整分辨率
  • matplotlib的Funcanimation类,虽然简单,但是遇到一次性调整多个artist的问题是,会变得相当棘手,比如一次更新多个点的位置,使用Funcanimation就不太香了【上面的2个案例均是一次更新1个对象,所以用Funcanimation】,使用ArtistAnimation可以帮助我们在每一帧,更新若干个artist对象。
  • ArtistAnimation是基于帧artist的一种动画创建方法,每一帧对应着一个artist的list,这些artist只会在这一帧显示,而所有的这些list组成一个大list,名叫artists,这个大list的每一个子list代表着每一帧的所有artist对象,从而渲染完整的动画。
import matplotlib.pyplot as plt
import matplotlib.animation as animationif __name__ == '__main__':x = [1,2,3,4,5,6,7,8,9,10]y = [1,2,3,4,5,6,7,8,9,10]fig = plt.figure()plt.xlim(0, 11)plt.ylim(0, 20)artists = []# 总共10帧,每帧10个点for i in range(10):frame = []for j in range(10):frame += plt.plot(x[j], y[j]+i, "o")    # 注意这里要+=,对列表操作而不是appandartists.append(frame)ani = animation.ArtistAnimation(fig=fig, artists=artists, repeat=False, interval=10)plt.show()ani.save('test.gif', dpi=600, fps=30)

Test4:雨滴模拟

该图是用Matplotlib实现的雨滴模拟,来源于Nicolas P. Rougier


但自己的电脑显示出了一些渲染问题(边框的图案有点问题),这部分问题可能和个人电脑相关,暂时想不到解决方案:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation# Fixing random state for reproducibility
np.random.seed(19680801)# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(0, 1), ax.set_xticks([])
ax.set_ylim(0, 1), ax.set_yticks([])# Create rain data
n_drops = 50
rain_drops = np.zeros(n_drops, dtype=[('position', float, 2),('size',     float, 1),('growth',   float, 1),('color',    float, 4)])# Initialize the raindrops in random positions and with
# random growth rates.
rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
rain_drops['growth'] = np.random.uniform(50, 200, n_drops)# Construct the scatter which we will update during animation
# as the raindrops develop.
scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],facecolors='none')def update(frame_number):# Get an index which we can use to re-spawn the oldest raindrop.current_index = frame_number % n_drops# Make all colors more transparent as time progresses.rain_drops['color'][:, 3] -= 1.0/len(rain_drops)rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)# Make all circles bigger.rain_drops['size'] += rain_drops['growth']# Pick a new position for oldest rain drop, resetting its size,# color and growth factor.rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)rain_drops['size'][current_index] = 5rain_drops['color'][current_index] = (0, 0, 0, 1)rain_drops['growth'][current_index] = np.random.uniform(50, 200)# Update the scatter collection, with the new colors, sizes and positions.scat.set_edgecolors(rain_drops['color'])scat.set_sizes(rain_drops['size'])scat.set_offsets(rain_drops['position'])# Construct the animation, using the update function as the animation director.
animation = FuncAnimation(fig, update, interval=10)
# plt.show()
animation.save('example4.gif', dpi=100, writer='pillow')

Other Test

还有一些其他的动图案例,如:柱状图的动画,脉冲星的假信号频率的比较路径演示,运动中流体中的流线绘制,等等,其原理大同小异。

最近还看到了2个优秀的动图可视化作品,拿出来分享一下。

优秀作品1

优秀作品2

References:

【1】 Python Matplotlib官网
【2】 数据可视化之美-动态图绘制(以Python为工具)

数据可视化之美-动态图绘制【补充】(以Python为工具)相关推荐

  1. python数据可视化之美源码_Python数据可视化之美-专业图

    Python数据可视化之美 专业图表绘制指南 作  者:张杰 著 定  价:129 出 版 社:电子工业出版社 出版日期:2020年03月01日 页  数:303 装  帧:平装 ISBN:97871 ...

  2. [转载] Python数据可视化库-Matplotlib——折线图绘制

    参考链接: Python Matplotlib数据可视化 plot折线图 # coding:utf-8 import pandas as pd import numpy as np from matp ...

  3. python数据可视化之美专业图表绘制指南_2019第23周:评《R语言数据可视化之美:专业图表绘制指南》...

    --- 大师,大师,618买的什么书呀,好奇呢. ··· 一本R语言绘图的书,可花了呢. "Beautiful Visualization with R" provides a c ...

  4. 用python把数据画成饼状图_Python学习第92课——数据可视化之饼状图绘制

    [每天几分钟,从零入门python编程的世界!] 假如一个行业只有ABCD四个公司,我们想要用图表展现,它们各自每年的生产总额,占整个行业的比例是多少,这时我们用饼状图(pie chart)更好. 假 ...

  5. python三维图能画地图_Python数据可视化:3D动态图,让你的足迹实现在地图上

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 以下文章来源于python数据分析之禅 ,作者小dull鸟 今天给大家带来一篇3 ...

  6. python画熊猫论文_Python数据可视化之美:专业图表绘制指南(全彩)

    Python数据可视化之美:专业图表绘制指南(全彩)电子书 系统性地介绍Python 的绘图语法系统,包括matplotlib.Seaborn.plotnine 包,以及用于地理空间数据可视化的Bas ...

  7. 数据可视化——R语言ggplot2包绘制相关矩阵为热图

    数据可视化--R语言ggplot2包绘制相关矩阵为热图 概述:R语言软件和数据可视化--ggplot2快速绘制相关矩阵为热图.本文翻译了一篇英文博客,博客原文链接:http://www.sthda.c ...

  8. 数据可视化——R语言ggplot2包绘制精美的小提琴图(并箱线图或误差条图组合)

    数据可视化--R语言ggplot2包绘制精美的小提琴图(并箱线图或误差条图组合) 概述:R语言使用ggplot2工具包绘制小提琴图.为了使数据表达更加丰富,同时将小提琴图与箱线图和误差条图相结合.另外 ...

  9. 【五一创作】数据可视化之美 ( 三 ) - 动图展示 ( Python Matlab )

    1 Introduction 在我们科研学习.工作生产中,将数据完美展现出来尤为重要. 数据可视化是以数据为视角,探索世界.我们真正想要的是 - 数据视觉,以数据为工具,以可视化为手段,目的是描述真实 ...

  10. matlab半小提琴图,数据可视化——Matlab平台matlab-barplot工具箱绘制小提琴图

    数据可视化--Matlab平台matlab-barplot工具箱绘制小提琴图 概述:基于matlab平台的matlab-barplot工具箱绘制小提琴图 小提琴图(violin plot)可以理解为另 ...

最新文章

  1. 2020年世界机器人报告
  2. js关闭窗口无提示,不支持FF
  3. OS中阻塞与挂起的区别sleep()的实现原理
  4. Android 开发(一)项目概况
  5. python代码转换为pytorch_pytorch使用 to 进行类型转换方式
  6. 程序员职业生涯的11个阶段程序人生
  7. 微信小程序流量主+直播开通和编码指南
  8. python之变量的私密处理
  9. opencv-api contourArea
  10. Linux shell基础(四)正则表达式与grep命令 beta
  11. Flutter进阶—自定义主题风格
  12. 中国料斗底部谷物拖车市场趋势报告、技术动态创新及市场预测
  13. php做异地登录验证,PHP实现用户异地登录提醒功能的方法【基于thinkPHP框架】
  14. mysql意外关闭xampp_错误:MySQL意外关闭xampp 3.2.4
  15. 虚机里的vCenter 迁移
  16. php怎么阻止页面跳转,php如何控制页面跳转
  17. node 没有界面的浏览器_了不起的Node-为什么要学习Nodejs
  18. IK摆锤冲击试验装置能在什么场合使用?
  19. Android APK反编译教程(带工具)
  20. 四叉树空间索引原理及其实现

热门文章

  1. wamp php打不开,wamp无法打开phpmyadmin
  2. 《正面管教》读后感_20171219
  3. 微信小程序开发工具的目录结构
  4. Gather-Excite:Exploiting Feature Context in Convolutional Neural Networks
  5. fatal: unsafe repository is owned by someone else 的解决方法
  6. JavaEE Day14 ServletHTTPRequest
  7. 计算机屏幕的显示分辨率与什么有关,计算机屏幕分辨率高低主要跟什么有关?...
  8. Pale Moon 苍月浏览器 24.0.1 发布
  9. 【PTA 6-10】输入多个单词,统计以指定字母开头的单词个数
  10. python print()什么意思_python print用法是什么