Matplotlib新手上路(下)
时间:2022-05-06
本文章向大家介绍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()
- 关于CPU使用率高的awr分析(r8笔记第46天)
- 图形工具和命令行的博弈-swingbench配置(r8笔记第63天)
- 手把手教你用LDA特征选择
- 一个关于执行计划的小问题测试(r8笔记第60天)
- 【Go 语言社区】www.golangweb.com通过工信部审核,正式挂牌社区域名
- golang 算法课程 正式开课--第一季 第1节
- 在 Mac OS X 装不上 TensorFlow?看了这篇就会装
- 利用python内置函数,快速统计单词在文本中出现的次数
- 物化视图刷新结合ADG的尝试(二)(r8笔记第57天)
- python 下利用os模块创建目录以及巧妙使用if not os.path.exits()创建
- Python读取json文件,并转化为字典进行提取字段(出现索引must be int,not str)解决方案
- Python 把字典的key和value的值取出来,按照顺序存入到list中
- Go语言 如果实现http重连?
- python strip()函数 删除字符串中无空白字符或者是无用字符
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 聊聊dubbo-go的DubboProtocol
- 推荐一个很牛叉的开源Flask项目
- 机器学习应用资产管理系列一:强化学习策略(附代码)
- 3分钟短文 | Laravel模型关联删除表记录,用观察者还是事件钩子
- 原理+代码|深入浅出Python随机森林预测实战
- 3分钟短文 | Laravel复杂SQL超多WHERE子句,本地作用域你没用过
- 3分钟短文 | Laravel同时连接多个数据库,你用啥办法?
- 3分钟短文 | PHP 连接2个字符串的8个方法,新手常犯错
- nodejs源码分析之connect
- 你应该了解的Nacos配置中心
- Jenkins CLI 命令行 v0.0.30
- 2020新鲜出炉的“面筋”,够刁钻
- Spring注解配置应该怎么玩
- 算法篇:链表之倒数第k个节点
- 彻底搞懂 Java 线程池,干啥都不再发憷