Hướng dẫn plot animation python - cốt truyện hoạt hình python

Matplotlib Phiên bản 1.1 đã thêm một số công cụ để tạo hình ảnh động thực sự lắt léo. Bạn có thể tìm thấy một số hình ảnh động ví dụ tốt trên trang ví dụ Matplotlib. Tôi nghĩ rằng tôi sẽ chia sẻ ở đây một số điều tôi đã học được khi chơi xung quanh với các công cụ này.

Hoạt hình cơ bản

Các công cụ hoạt hình trung tâm xung quanh lớp cơ sở

"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
8, cung cấp một khung xung quanh mà chức năng hoạt hình được xây dựng. Các giao diện chính là
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
9 và
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
0, mà bạn có thể đọc thêm về tài liệu. Ở đây tôi sẽ khám phá bằng công cụ
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
0 mà tôi thấy là hữu ích nhất.

Trước tiên, chúng tôi sẽ sử dụng

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
0 để thực hiện một hình ảnh động cơ bản của sóng hình sin di chuyển trên màn hình:

Hoạt hình cơ bản BASIC_ANIMATION.PY download
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
00000 download
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
download
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

Hãy bước qua điều này và xem những gì đang xảy ra. Sau khi nhập các phần yêu cầu của

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
2 và
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
3, tập lệnh đã thiết lập cốt truyện:
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

Ở đây chúng tôi tạo một cửa sổ hình, tạo một trục duy nhất trong hình và sau đó tạo đối tượng dòng của chúng tôi sẽ được sửa đổi trong hình ảnh động. Lưu ý rằng ở đây chúng tôi chỉ cần vẽ một dòng trống: Chúng tôi sẽ thêm dữ liệu vào dòng sau.

Tiếp theo, chúng tôi sẽ tạo các chức năng làm cho hoạt hình xảy ra.

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
4 là chức năng sẽ được gọi để tạo khung cơ sở mà hình ảnh động diễn ra. Ở đây chúng tôi chỉ sử dụng một hàm đơn giản đặt dữ liệu dòng thành không có gì. Điều quan trọng là chức năng này trả về đối tượng dòng, bởi vì điều này cho người hoạt hình đối tượng trên lô để cập nhật sau mỗi khung hình:
def init():
    line.set_data([], [])
    return line,

Phần tiếp theo là chức năng hoạt hình. Nó có một tham số duy nhất, số khung

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
5 và vẽ sóng hình sin với sự thay đổi phụ thuộc vào
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
5:
# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

Lưu ý rằng một lần nữa ở đây, chúng tôi trả lại một tuple của các đối tượng cốt truyện đã được sửa đổi. Điều này cho khung hoạt hình những phần của cốt truyện nên được hoạt hình.

Cuối cùng, chúng tôi tạo đối tượng hoạt hình:

"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
0

Đối tượng này cần phải tồn tại, vì vậy nó phải được gán cho một biến. Chúng tôi đã chọn hoạt hình 100 khung hình với độ trễ 20ms giữa các khung. Từ khóa

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
7 là một từ khóa quan trọng: điều này cho hoạt hình chỉ vẽ lại các phần của cốt truyện đã thay đổi. Thời gian lưu với
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
8 có nghĩa là hình ảnh động hiển thị nhanh hơn nhiều.

Chúng tôi kết thúc với một lệnh lưu tùy chọn, và sau đó là lệnh hiển thị kết quả. Đây là những gì tập lệnh tạo ra:

Khung này để tạo và lưu hoạt hình rất mạnh mẽ và linh hoạt: nếu chúng ta đưa một số vật lý vào chức năng

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
9, khả năng là vô tận. Dưới đây là một vài ví dụ về một số hình ảnh động vật lý mà tôi đã chơi xung quanh.

Con lắc kép

Một trong những ví dụ được cung cấp trên trang ví dụ Matplotlib là một hình ảnh động của một con lắc kép. Ví dụ này hoạt động bằng cách tính toán vị trí con lắc trong hơn 10 giây, và sau đó hoạt hình kết quả. Tôi đã thấy điều này và tự hỏi liệu Python có đủ nhanh để tính toán động lực học không. Hóa ra nó là:

Double Pendulum double_pendulum.py download
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
4 download
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
4
download
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
4

Ở đây chúng tôi đã tạo ra một lớp lưu trữ trạng thái của con lắc kép (được mã hóa theo góc của mỗi cánh tay cộng với vận tốc góc của mỗi cánh tay) và cũng cung cấp một số chức năng để tính toán động lực học. Các hàm hoạt hình giống như trên, nhưng chúng ta chỉ có chức năng cập nhật phức tạp hơn một chút: nó không chỉ thay đổi vị trí của các điểm mà còn thay đổi văn bản để theo dõi thời gian và năng lượng (năng lượng phải không đổi nếu toán học của chúng ta là chính xác: đó là sự an ủi như vậy). Video dưới đây chỉ kéo dài mười giây, nhưng bằng cách chạy tập lệnh, bạn có thể xem con lắc dao động một cách hỗn loạn cho đến khi máy tính xách tay của bạn hết điện:

Các hạt trong hộp

Một hình ảnh động khác mà tôi tạo ra là sự va chạm đàn hồi của một nhóm các hạt trong một hộp dưới lực hấp dẫn. Các va chạm là đàn hồi: chúng bảo tồn năng lượng và động lượng 2D, và các hạt nảy ra một cách thực tế khỏi các bức tường của hộp và rơi vào ảnh hưởng của một lực hấp dẫn không đổi:

Các hạt trong hộp Hạt_box.py Tải xuống
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
66 download
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
6
download
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: 
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
6

Toán học nên quen thuộc với bất cứ ai có nền tảng vật lý, và kết quả là khá mê hoặc. Tôi đã mã hóa nó trong một chuyến bay, và cuối cùng chỉ ngồi và xem nó trong khoảng mười phút.

Đây chỉ là khởi đầu: nó có thể là một bài tập thú vị để thêm các yếu tố khác, như tính toán nhiệt độ và áp suất để chứng minh luật khí lý tưởng, hoặc vẽ sơ đồ thời gian thực của phân phối vận tốc để theo dõi nó tiếp cận phân phối Maxwellian dự kiến. Nó mở ra nhiều khả năng cho các bản demo vật lý ảo ...

Tóm tắt nó lên

Mô -đun hoạt hình Matplotlib là một bổ sung tuyệt vời cho những gì đã là một gói tuyệt vời.Tôi nghĩ rằng tôi đã gãi bề mặt của những gì có thể với các công cụ này ... bạn có thể nghĩ ra ý tưởng hoạt hình tuyệt vời nào?

Chỉnh sửa: Trong một bài đăng tiếp theo, tôi chỉ ra cách các công cụ này có thể được sử dụng để tạo hoạt hình của một hệ thống cơ học lượng tử đơn giản.