Matplotlib新手上路(下)
接上篇继续,这次来演示下如何做动画,以及加载图片
一、动画图
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation fig, ax = plt.subplots() x = np.arange(0, 2 * np.pi, 0.01)
line, = ax.plot(x, np.sin(x)) def init():
line.set_ydata([np.nan] * len(x)) # Y轴值归0,Mac上加不加这句,都一样
return line, def animate(i):
line.set_ydata(np.sin(x + i / 100)) # update the data.
return line, ani = animation.FuncAnimation(
# blit在Mac上只能设置False,否则动画有残影
fig, animate, init_func=init, interval=2, blit=False, save_count=50) init() plt.show()
基本套路是:init()函数中给定图象的初始状态,然后animate()函数中每次对函数图象动态调整一点点,最后用FuncAnimation把它们串起来。
再来看一个官网给的比较好玩的示例:
from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation G = 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 kg def 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])) / den1 dydx[2] = state[3] den2 = (L2 / L1) * den1
dydx[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])) / den2 return 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]) + y1 fig = 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_text def 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_text ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)),
interval=25, blit=False, init_func=init) plt.show()
甚至还可以创建一些艺术气息的动画:
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=(5, 5))
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.3, 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] = 5
rain_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()

二、加载图片
import matplotlib.pyplot as plt
import matplotlib.image as mpimg img = mpimg.imread('cat.png') # 随便从网上捞的一张图片,保存到当前目录下
lum_img = img[:, :, 0] # plt.figure()
plt.subplot(331)
plt.imshow(img) plt.subplot(332)
plt.imshow(lum_img) plt.subplot(333)
plt.imshow(lum_img, cmap="spring") plt.subplot(334)
plt.imshow(lum_img, cmap="summer") plt.subplot(335)
plt.imshow(lum_img, cmap="autumn") plt.subplot(336)
plt.imshow(lum_img, cmap="winter") plt.subplot(337)
plt.imshow(lum_img, cmap="hot") plt.subplot(338)
plt.imshow(lum_img, cmap="cool") plt.subplot(339)
plt.imshow(lum_img, cmap="bone") plt.show()

Matplotlib新手上路(下)的更多相关文章
- Matplotlib新手上路(中)
接上回继续 一.多张图布局(subplot) 1.1 subplot布局方式 import matplotlib.pyplot as plt plt.figure() plt.subplot(3, 2 ...
- Matplotlib新手上路(上)
matplotlib是python里用于绘图的专用包,功能十分强大.下面介绍一些最基本的用法: 一.最基本的划线 先来一个简单的示例,代码如下,已经加了注释: import matplotlib.py ...
- php大力力 [001节]2015-08-21.php在百度文库的几个基础教程新手上路日记 大力力php 大力同学 2015-08-21 15:28
php大力力 [001节]2015-08-21.php在百度文库的几个基础教程新手上路日记 大力力php 大力同学 2015-08-21 15:28 话说,嗯嗯,就是我自己说,做事认真要用表格,学习技 ...
- OpenGL教程之新手上路
Jeff Molofee(NeHe)的OpenGL教程- 新手上路 译者的话:NeHe的教程一共同拥有30多课,内容翔实,而且不断更新 .国内的站点实在应该向他们学习.令人吃惊的是,NeHe提供的例程 ...
- webpack4配置详解之新手上路初探
前言 经常会有群友问起webpack.react.redux.甚至create-react-app配置等等方面的问题,有些是我也不懂的,慢慢从大家的相互交流中,也学到了不少. 今天就尝试着一起来聊 ...
- 转-spring-boot 注解配置mybatis+druid(新手上路)-http://blog.csdn.net/sinat_36203615/article/details/53759935
spring-boot 注解配置mybatis+druid(新手上路) 转载 2016年12月20日 10:17:17 标签: sprinb-boot / mybatis / druid 10475 ...
- Ocelot 新手上路
新手上路,老司机请多多包含!Ocelot 在博园里文章特别多,但是按照其中一篇文章教程,如果经验很少或者小白,是没法将程序跑向博主的结果. 因此总结下 参考多篇文章,终于达到预期效果. Oce ...
- 新手上路——it人如何保持竞争力
新手上路——如何保持竞争力 JINGZHENGLI 套用葛大爷的一句名言:21世纪什么最贵,人才.哪你是人才还是人材?还是人财或人裁?相信大家都不是最后一种.何如保持住这个光环呢?就需要我们保持我们独 ...
- Dart语言快速学习上手(新手上路)
Dart语言快速学习上手(新手上路) // 声明返回值 int add(int a, int b) { return a + b; } // 不声明返回值 add2(int a, int b) { r ...
随机推荐
- js 将图片连接转换称base64格式
我们把图像文件的内容直接写在了HTML 文件中,这样做的好处是,节省了一个HTTP 请求.坏处呢,就是浏览器不会缓存这种图像.现在我们提供一个js: function convertImgToBase ...
- robotium之不标准select控件
今天写脚本,遇到一个联合查询框 即:下拉框选择,输入框输入搜索条件,点击查询按钮 如图样式: 用uiautomatorviewer查看元素:无ID,无name,无desc 看到这我瞬间尴尬了,该咋办呢 ...
- Deep Learning系统实训之三:卷积神经网络
边界填充(padding):卷积过程中,越靠近图片中间位置的像素点越容易被卷积计算多次,越靠近边缘的像素点被卷积计算的次数越少,填充就是为了使原来边缘像素点的位置变得相对靠近中部,而我们又不想让填充的 ...
- PHP实现简单倒计时
PHP实现倒计时代码示例如下: <?php $time1 = time(); $time2 = strtotime("2018-10-1"); $time3 = strtot ...
- PHP PC端微信扫码支付【模式二】详细教程-附带源码(转)
博主写这破玩意儿的时候花了大概快两天时间才整体的弄懂逻辑,考虑了一下~还是把所有代码都放出来给大家~抱着开源大无私的精神!谁叫我擅长拍黄片呢?同时也感谢我刚入行时候那些无私帮过我的程序员们! 首先还是 ...
- hdu 2197 求长度为n的本原串 (快速幂+map)
Problem Description由0和1组成的串中,不能表示为由几个相同的较小的串连接成的串,称为本原串,有多少个长为n(n<=100000000)的本原串?答案mod2008.例如,10 ...
- java快速排序引起的StackOverflowError异常
写在前面:这篇随笔主要记录一下递归调用引起的虚拟机栈溢出的情况以及通过参数配置了虚拟机栈大小来使递归调用可以顺利执行.并没有对涉及到的一些概念进行详细的解释(因为我自己目前对这些概念并不是特别清楚), ...
- Struts2中的数据处理的三种方式对比(Action中三种作用域request,session,application对象)
1:在Action中如何获得作用域(request,session,application)对象: 取得Map(键值对映射集)类型的requet,session,application; 对数据操作的 ...
- 微信WebView关闭后本地cookie无法清除问题
问题背景 在微信WebView下的页面中登录后,关闭WebView返回后再次进入页面,发现登录态还存在,原因是微信不会主动清除cookie以及其他的缓存. 期望是关闭窗口后会清除cookie,重新进入 ...
- BZOJ3377 [Usaco2004 Open]The Cow Lineup 奶牛序列 其他
欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ3377 题意概括 给出一个序列,序列中的数字为1~k中的. 让你求最短的非子序列长度. 题解 我们把 ...