mirror of
https://github.com/Estom/notes.git
synced 2026-04-05 03:48:56 +08:00
matplotlib & pandas
This commit is contained in:
59
Python/matplotlab/gallery/animation/animate_decay.md
Normal file
59
Python/matplotlab/gallery/animation/animate_decay.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# 衰变
|
||||
|
||||
这个例子展示了:
|
||||
- 使用生成器来驱动动画,
|
||||
- 在动画期间更改轴限制。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.animation as animation
|
||||
|
||||
|
||||
def data_gen(t=0):
|
||||
cnt = 0
|
||||
while cnt < 1000:
|
||||
cnt += 1
|
||||
t += 0.1
|
||||
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
|
||||
|
||||
|
||||
def init():
|
||||
ax.set_ylim(-1.1, 1.1)
|
||||
ax.set_xlim(0, 10)
|
||||
del xdata[:]
|
||||
del ydata[:]
|
||||
line.set_data(xdata, ydata)
|
||||
return line,
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
line, = ax.plot([], [], lw=2)
|
||||
ax.grid()
|
||||
xdata, ydata = [], []
|
||||
|
||||
|
||||
def run(data):
|
||||
# update the data
|
||||
t, y = data
|
||||
xdata.append(t)
|
||||
ydata.append(y)
|
||||
xmin, xmax = ax.get_xlim()
|
||||
|
||||
if t >= xmax:
|
||||
ax.set_xlim(xmin, 2*xmax)
|
||||
ax.figure.canvas.draw()
|
||||
line.set_data(xdata, ydata)
|
||||
|
||||
return line,
|
||||
|
||||
ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
|
||||
repeat=False, init_func=init)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: animate_decay.py](https://matplotlib.org/_downloads/animate_decay.py)
|
||||
- [下载Jupyter notebook: animate_decay.ipynb](https://matplotlib.org/_downloads/animate_decay.ipynb)
|
||||
89
Python/matplotlab/gallery/animation/animated_histogram.md
Normal file
89
Python/matplotlab/gallery/animation/animated_histogram.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# 动画直方图
|
||||
|
||||
使用路径补丁为动画直方图绘制一堆矩形。
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.patches as patches
|
||||
import matplotlib.path as path
|
||||
import matplotlib.animation as animation
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
# histogram our data with numpy
|
||||
data = np.random.randn(1000)
|
||||
n, bins = np.histogram(data, 100)
|
||||
|
||||
# get the corners of the rectangles for the histogram
|
||||
left = np.array(bins[:-1])
|
||||
right = np.array(bins[1:])
|
||||
bottom = np.zeros(len(left))
|
||||
top = bottom + n
|
||||
nrects = len(left)
|
||||
```
|
||||
|
||||
这里有一个棘手的部分 - 我们必须为每个rect使用 ``plt.Path.MOVETO``,``plt.Path.LINETO``和``plt.Path.CLOSEPOLY``设置顶点和路径代码数组。
|
||||
|
||||
- 每个矩形我们需要1个 ``MOVETO``,它设置了初始点。
|
||||
- 我们需要3个``LINETO``,它告诉Matplotlib从顶点1到顶点2,v2到v3和v3到v4绘制线。
|
||||
- 然后我们需要一个``CLOSEPOLY``,它告诉Matplotlib从v4到我们的初始顶点(MOVETO顶点)绘制一条线,以便关闭多边形。
|
||||
|
||||
**注意:**CLOSEPOLY的顶点被忽略,但我们仍然需要在verts数组中使用占位符来保持代码与顶点对齐。
|
||||
|
||||
```python
|
||||
nverts = nrects * (1 + 3 + 1)
|
||||
verts = np.zeros((nverts, 2))
|
||||
codes = np.ones(nverts, int) * path.Path.LINETO
|
||||
codes[0::5] = path.Path.MOVETO
|
||||
codes[4::5] = path.Path.CLOSEPOLY
|
||||
verts[0::5, 0] = left
|
||||
verts[0::5, 1] = bottom
|
||||
verts[1::5, 0] = left
|
||||
verts[1::5, 1] = top
|
||||
verts[2::5, 0] = right
|
||||
verts[2::5, 1] = top
|
||||
verts[3::5, 0] = right
|
||||
verts[3::5, 1] = bottom
|
||||
```
|
||||
|
||||
为了给直方图设置动画,我们需要一个动画函数,它生成一组随机数字并更新直方图顶点的位置(在这种情况下,只有每个矩形的高度)。 补丁最终将成为补丁对象。
|
||||
|
||||
```python
|
||||
patch = None
|
||||
|
||||
|
||||
def animate(i):
|
||||
# simulate new data coming in
|
||||
data = np.random.randn(1000)
|
||||
n, bins = np.histogram(data, 100)
|
||||
top = bottom + n
|
||||
verts[1::5, 1] = top
|
||||
verts[2::5, 1] = top
|
||||
return [patch, ]
|
||||
```
|
||||
|
||||
现在我们使用顶点和代码为直方图构建Path和Patch实例。 我们将补丁添加到Axes实例,并使用我们的animate函数设置``FuncAnimation``。
|
||||
|
||||
```python
|
||||
fig, ax = plt.subplots()
|
||||
barpath = path.Path(verts, codes)
|
||||
patch = patches.PathPatch(
|
||||
barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
|
||||
ax.add_patch(patch)
|
||||
|
||||
ax.set_xlim(left[0], right[-1])
|
||||
ax.set_ylim(bottom.min(), top.max())
|
||||
|
||||
ani = animation.FuncAnimation(fig, animate, 100, repeat=False, blit=True)
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: animated_histogram.py](https://matplotlib.org/_downloads/animated_histogram.py)
|
||||
- [下载Jupyter notebook: animated_histogram.ipynb](https://matplotlib.org/_downloads/animated_histogram.ipynb)
|
||||
33
Python/matplotlab/gallery/animation/animation_demo.md
Normal file
33
Python/matplotlab/gallery/animation/animation_demo.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# pyplot动画
|
||||
|
||||
通过调用绘图命令之间的[暂停](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pause.html#matplotlib.pyplot.pause)来生成动画。
|
||||
|
||||
此处显示的方法仅适用于简单,低性能的使用。 对于要求更高的应用程序,请查看``动画模块``和使用它的示例。
|
||||
|
||||
请注意,调用[time.sleep](https://docs.python.org/3/library/time.html#time.sleep)而不是[暂停](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pause.html#matplotlib.pyplot.pause)将不起作用。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
np.random.seed(19680801)
|
||||
data = np.random.random((50, 50, 50))
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
|
||||
for i in range(len(data)):
|
||||
ax.cla()
|
||||
ax.imshow(data[i])
|
||||
ax.set_title("frame {}".format(i))
|
||||
# Note that using time.sleep does *not* work here!
|
||||
plt.pause(0.1)
|
||||
```
|
||||
|
||||
**脚本总运行时间:**(0分7.211秒)
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: animation_demo.py](https://matplotlib.org/_downloads/animation_demo.py)
|
||||
- [下载Jupyter notebook: animation_demo.ipynb](https://matplotlib.org/_downloads/animation_demo.ipynb)
|
||||
71
Python/matplotlab/gallery/animation/bayes_update.md
Normal file
71
Python/matplotlab/gallery/animation/bayes_update.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# 贝叶斯更新
|
||||
|
||||
此动画显示在新数据到达时重新安装的后验估计更新。
|
||||
|
||||
垂直线表示绘制的分布应该收敛的理论值。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.animation import FuncAnimation
|
||||
|
||||
|
||||
def beta_pdf(x, a, b):
|
||||
return (x**(a-1) * (1-x)**(b-1) * math.gamma(a + b)
|
||||
/ (math.gamma(a) * math.gamma(b)))
|
||||
|
||||
|
||||
class UpdateDist(object):
|
||||
def __init__(self, ax, prob=0.5):
|
||||
self.success = 0
|
||||
self.prob = prob
|
||||
self.line, = ax.plot([], [], 'k-')
|
||||
self.x = np.linspace(0, 1, 200)
|
||||
self.ax = ax
|
||||
|
||||
# Set up plot parameters
|
||||
self.ax.set_xlim(0, 1)
|
||||
self.ax.set_ylim(0, 15)
|
||||
self.ax.grid(True)
|
||||
|
||||
# This vertical line represents the theoretical value, to
|
||||
# which the plotted distribution should converge.
|
||||
self.ax.axvline(prob, linestyle='--', color='black')
|
||||
|
||||
def init(self):
|
||||
self.success = 0
|
||||
self.line.set_data([], [])
|
||||
return self.line,
|
||||
|
||||
def __call__(self, i):
|
||||
# This way the plot can continuously run and we just keep
|
||||
# watching new realizations of the process
|
||||
if i == 0:
|
||||
return self.init()
|
||||
|
||||
# Choose success based on exceed a threshold with a uniform pick
|
||||
if np.random.rand(1,) < self.prob:
|
||||
self.success += 1
|
||||
y = beta_pdf(self.x, self.success + 1, (i - self.success) + 1)
|
||||
self.line.set_data(self.x, y)
|
||||
return self.line,
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ud = UpdateDist(ax, prob=0.7)
|
||||
anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init,
|
||||
interval=100, blit=True)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: bayes_update.py](https://matplotlib.org/_downloads/bayes_update.py)
|
||||
- [下载Jupyter notebook: bayes_update.ipynb](https://matplotlib.org/_downloads/bayes_update.ipynb)
|
||||
@@ -0,0 +1,99 @@
|
||||
# 双摆问题
|
||||
|
||||
这个动画说明了双摆问题。
|
||||
|
||||
双摆公式从 http://www.physics.usyd.edu.au/~wheat/dpend_html/solve_dpend.c 的C代码翻译而来。
|
||||
|
||||
```python
|
||||
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=True, init_func=init)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: double_pendulum_sgskip.py](https://matplotlib.org/_downloads/double_pendulum_sgskip.py)
|
||||
- [下载Jupyter notebook: double_pendulum_sgskip.ipynb](https://matplotlib.org/_downloads/double_pendulum_sgskip.ipynb)
|
||||
47
Python/matplotlab/gallery/animation/dynamic_image.md
Normal file
47
Python/matplotlab/gallery/animation/dynamic_image.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# 使用预先计算的图像列表的动画图像
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.animation as animation
|
||||
|
||||
fig = plt.figure()
|
||||
|
||||
|
||||
def f(x, y):
|
||||
return np.sin(x) + np.cos(y)
|
||||
|
||||
x = np.linspace(0, 2 * np.pi, 120)
|
||||
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
|
||||
# ims is a list of lists, each row is a list of artists to draw in the
|
||||
# current frame; here we are just animating one artist, the image, in
|
||||
# each frame
|
||||
ims = []
|
||||
for i in range(60):
|
||||
x += np.pi / 15.
|
||||
y += np.pi / 20.
|
||||
im = plt.imshow(f(x, y), animated=True)
|
||||
ims.append([im])
|
||||
|
||||
ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
|
||||
repeat_delay=1000)
|
||||
|
||||
# To save the animation, use e.g.
|
||||
#
|
||||
# ani.save("movie.mp4")
|
||||
#
|
||||
# or
|
||||
#
|
||||
# from matplotlib.animation import FFMpegWriter
|
||||
# writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
|
||||
# ani.save("movie.mp4", writer=writer)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: dynamic_image.py](https://matplotlib.org/_downloads/dynamic_image.py)
|
||||
- [下载Jupyter notebook: dynamic_image.ipynb](https://matplotlib.org/_downloads/dynamic_image.ipynb)
|
||||
39
Python/matplotlab/gallery/animation/frame_grabbing_sgskip.md
Normal file
39
Python/matplotlab/gallery/animation/frame_grabbing_sgskip.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# 帧抓取
|
||||
|
||||
直接使用MovieWriter抓取单个帧并将其写入文件。 这避免了任何事件循环集成,因此甚至可以与Agg后端一起使用。 建议不要在交互式设置中使用。
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.animation import FFMpegWriter
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
|
||||
metadata = dict(title='Movie Test', artist='Matplotlib',
|
||||
comment='Movie support!')
|
||||
writer = FFMpegWriter(fps=15, metadata=metadata)
|
||||
|
||||
fig = plt.figure()
|
||||
l, = plt.plot([], [], 'k-o')
|
||||
|
||||
plt.xlim(-5, 5)
|
||||
plt.ylim(-5, 5)
|
||||
|
||||
x0, y0 = 0, 0
|
||||
|
||||
with writer.saving(fig, "writer_test.mp4", 100):
|
||||
for i in range(100):
|
||||
x0 += 0.1 * np.random.randn()
|
||||
y0 += 0.1 * np.random.randn()
|
||||
l.set_data(x0, y0)
|
||||
writer.grab_frame()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: frame_grabbing_sgskip.py](https://matplotlib.org/_downloads/frame_grabbing_sgskip.py)
|
||||
- [下载Jupyter notebook: frame_grabbing_sgskip.ipynb](https://matplotlib.org/_downloads/frame_grabbing_sgskip.ipynb)
|
||||
75
Python/matplotlab/gallery/animation/rain.md
Normal file
75
Python/matplotlab/gallery/animation/rain.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# 雨模拟
|
||||
|
||||
通过设置50个散点的比例和不透明度来模拟表面上的雨滴。
|
||||
|
||||
作者:Nicolas P. Rougier
|
||||
|
||||

|
||||
|
||||
```python
|
||||
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] = 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()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: rain.py](https://matplotlib.org/_downloads/rain.py)
|
||||
- [下载Jupyter notebook: rain.ipynb](https://matplotlib.org/_downloads/rain.ipynb)
|
||||
75
Python/matplotlab/gallery/animation/random_walk.md
Normal file
75
Python/matplotlab/gallery/animation/random_walk.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# 动画3D随机游走
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import mpl_toolkits.mplot3d.axes3d as p3
|
||||
import matplotlib.animation as animation
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
|
||||
def Gen_RandLine(length, dims=2):
|
||||
"""
|
||||
Create a line using a random walk algorithm
|
||||
|
||||
length is the number of points for the line.
|
||||
dims is the number of dimensions the line has.
|
||||
"""
|
||||
lineData = np.empty((dims, length))
|
||||
lineData[:, 0] = np.random.rand(dims)
|
||||
for index in range(1, length):
|
||||
# scaling the random numbers by 0.1 so
|
||||
# movement is small compared to position.
|
||||
# subtraction by 0.5 is to change the range to [-0.5, 0.5]
|
||||
# to allow a line to move backwards.
|
||||
step = ((np.random.rand(dims) - 0.5) * 0.1)
|
||||
lineData[:, index] = lineData[:, index - 1] + step
|
||||
|
||||
return lineData
|
||||
|
||||
|
||||
def update_lines(num, dataLines, lines):
|
||||
for line, data in zip(lines, dataLines):
|
||||
# NOTE: there is no .set_data() for 3 dim data...
|
||||
line.set_data(data[0:2, :num])
|
||||
line.set_3d_properties(data[2, :num])
|
||||
return lines
|
||||
|
||||
# Attaching 3D axis to the figure
|
||||
fig = plt.figure()
|
||||
ax = p3.Axes3D(fig)
|
||||
|
||||
# Fifty lines of random 3-D lines
|
||||
data = [Gen_RandLine(25, 3) for index in range(50)]
|
||||
|
||||
# Creating fifty line objects.
|
||||
# NOTE: Can't pass empty arrays into 3d version of plot()
|
||||
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]
|
||||
|
||||
# Setting the axes properties
|
||||
ax.set_xlim3d([0.0, 1.0])
|
||||
ax.set_xlabel('X')
|
||||
|
||||
ax.set_ylim3d([0.0, 1.0])
|
||||
ax.set_ylabel('Y')
|
||||
|
||||
ax.set_zlim3d([0.0, 1.0])
|
||||
ax.set_zlabel('Z')
|
||||
|
||||
ax.set_title('3D Test')
|
||||
|
||||
# Creating the Animation object
|
||||
line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),
|
||||
interval=50, blit=False)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: random_walk.py](https://matplotlib.org/_downloads/random_walk.py)
|
||||
- [下载Jupyter notebook: random_walk.ipynb](https://matplotlib.org/_downloads/random_walk.ipynb)
|
||||
45
Python/matplotlab/gallery/animation/simple_anim.md
Normal file
45
Python/matplotlab/gallery/animation/simple_anim.md
Normal file
@@ -0,0 +1,45 @@
|
||||
# 动画线图
|
||||
|
||||

|
||||
|
||||
```python
|
||||
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(): # only required for blitting to give a clean slate.
|
||||
line.set_ydata([np.nan] * len(x))
|
||||
return line,
|
||||
|
||||
|
||||
def animate(i):
|
||||
line.set_ydata(np.sin(x + i / 100)) # update the data.
|
||||
return line,
|
||||
|
||||
|
||||
ani = animation.FuncAnimation(
|
||||
fig, animate, init_func=init, interval=2, blit=True, save_count=50)
|
||||
|
||||
# To save the animation, use e.g.
|
||||
#
|
||||
# ani.save("movie.mp4")
|
||||
#
|
||||
# or
|
||||
#
|
||||
# from matplotlib.animation import FFMpegWriter
|
||||
# writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
|
||||
# ani.save("movie.mp4", writer=writer)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: simple_anim.py](https://matplotlib.org/_downloads/simple_anim.py)
|
||||
- [下载Jupyter notebook: simple_anim.ipynb](https://matplotlib.org/_downloads/simple_anim.ipynb)
|
||||
67
Python/matplotlab/gallery/animation/strip_chart.md
Normal file
67
Python/matplotlab/gallery/animation/strip_chart.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# 示波器
|
||||
|
||||
模拟示波器。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
from matplotlib.lines import Line2D
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.animation as animation
|
||||
|
||||
|
||||
class Scope(object):
|
||||
def __init__(self, ax, maxt=2, dt=0.02):
|
||||
self.ax = ax
|
||||
self.dt = dt
|
||||
self.maxt = maxt
|
||||
self.tdata = [0]
|
||||
self.ydata = [0]
|
||||
self.line = Line2D(self.tdata, self.ydata)
|
||||
self.ax.add_line(self.line)
|
||||
self.ax.set_ylim(-.1, 1.1)
|
||||
self.ax.set_xlim(0, self.maxt)
|
||||
|
||||
def update(self, y):
|
||||
lastt = self.tdata[-1]
|
||||
if lastt > self.tdata[0] + self.maxt: # reset the arrays
|
||||
self.tdata = [self.tdata[-1]]
|
||||
self.ydata = [self.ydata[-1]]
|
||||
self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)
|
||||
self.ax.figure.canvas.draw()
|
||||
|
||||
t = self.tdata[-1] + self.dt
|
||||
self.tdata.append(t)
|
||||
self.ydata.append(y)
|
||||
self.line.set_data(self.tdata, self.ydata)
|
||||
return self.line,
|
||||
|
||||
|
||||
def emitter(p=0.03):
|
||||
'return a random value with probability p, else 0'
|
||||
while True:
|
||||
v = np.random.rand(1)
|
||||
if v > p:
|
||||
yield 0.
|
||||
else:
|
||||
yield np.random.rand(1)
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
scope = Scope(ax)
|
||||
|
||||
# pass a generator in "emitter" to produce data for the update func
|
||||
ani = animation.FuncAnimation(fig, scope.update, emitter, interval=10,
|
||||
blit=True)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: strip_chart.py](https://matplotlib.org/_downloads/strip_chart.py)
|
||||
- [下载Jupyter notebook: strip_chart.ipynb](https://matplotlib.org/_downloads/strip_chart.ipynb)
|
||||
77
Python/matplotlab/gallery/animation/unchained.md
Normal file
77
Python/matplotlab/gallery/animation/unchained.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# MATPLOTLIB UNCHAINED
|
||||
|
||||
脉冲星的假信号频率的比较路径演示(主要是因为Joy Division的未知乐趣的封面而闻名)。
|
||||
|
||||
作者:Nicolas P. Rougier
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.animation as animation
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
|
||||
# Create new Figure with black background
|
||||
fig = plt.figure(figsize=(8, 8), facecolor='black')
|
||||
|
||||
# Add a subplot with no frame
|
||||
ax = plt.subplot(111, frameon=False)
|
||||
|
||||
# Generate random data
|
||||
data = np.random.uniform(0, 1, (64, 75))
|
||||
X = np.linspace(-1, 1, data.shape[-1])
|
||||
G = 1.5 * np.exp(-4 * X ** 2)
|
||||
|
||||
# Generate line plots
|
||||
lines = []
|
||||
for i in range(len(data)):
|
||||
# Small reduction of the X extents to get a cheap perspective effect
|
||||
xscale = 1 - i / 200.
|
||||
# Same for linewidth (thicker strokes on bottom)
|
||||
lw = 1.5 - i / 100.0
|
||||
line, = ax.plot(xscale * X, i + G * data[i], color="w", lw=lw)
|
||||
lines.append(line)
|
||||
|
||||
# Set y limit (or first line is cropped because of thickness)
|
||||
ax.set_ylim(-1, 70)
|
||||
|
||||
# No ticks
|
||||
ax.set_xticks([])
|
||||
ax.set_yticks([])
|
||||
|
||||
# 2 part titles to get different font weights
|
||||
ax.text(0.5, 1.0, "MATPLOTLIB ", transform=ax.transAxes,
|
||||
ha="right", va="bottom", color="w",
|
||||
family="sans-serif", fontweight="light", fontsize=16)
|
||||
ax.text(0.5, 1.0, "UNCHAINED", transform=ax.transAxes,
|
||||
ha="left", va="bottom", color="w",
|
||||
family="sans-serif", fontweight="bold", fontsize=16)
|
||||
|
||||
|
||||
def update(*args):
|
||||
# Shift all data to the right
|
||||
data[:, 1:] = data[:, :-1]
|
||||
|
||||
# Fill-in new values
|
||||
data[:, 0] = np.random.uniform(0, 1, len(data))
|
||||
|
||||
# Update data
|
||||
for i in range(len(data)):
|
||||
lines[i].set_ydata(i + G * data[i])
|
||||
|
||||
# Return modified artists
|
||||
return lines
|
||||
|
||||
# Construct the animation, using the update function as the animation director.
|
||||
anim = animation.FuncAnimation(fig, update, interval=10)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: unchained.py](https://matplotlib.org/_downloads/unchained.py)
|
||||
- [下载Jupyter notebook: unchained.ipynb](https://matplotlib.org/_downloads/unchained.ipynb)
|
||||
Reference in New Issue
Block a user