>  기사  >  백엔드 개발  >  matplotlib를 통한 Python 간단한 그리기 애니메이션 예제

matplotlib를 통한 Python 간단한 그리기 애니메이션 예제

小云云
小云云원래의
2017-12-14 10:42:193624검색

Matplotlib는 다양한 하드카피 형식과 크로스 플랫폼 대화형 환경에서 출판 품질의 그래픽을 생성하는 Python용 2D 플로팅 라이브러리입니다. Matplotlib를 사용하면 개발자는 단 몇 줄의 코드만으로 플롯, 히스토그램, 전력 스펙트럼, 막대 차트, 오류 플롯, 산점도 등을 생성할 수 있습니다. 이 글은 주로 matplotlib을 통해 Python 그리기 애니메이션의 간단한 예를 소개하는데, 이는 특정 참조 가치가 있습니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

matplotlib는 버전 1.1.0부터 애니메이션 그리기를 지원했습니다. 구체적인 사용법은 공식 도움말 문서를 참조하세요. 다음은 매우 기본적인 예입니다.

"""
A simple example of an animated plot
"""
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()
# create our line object which will be modified in the animation
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
# we simply plot an empty line: we'll add data to the line later
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
# It takes a single parameter, the frame number i 
def animate(i):
 x = np.linspace(0, 2, 1000)
 y = np.sin(2 * np.pi * (x - 0.01 * i)) # update the data
 line.set_data(x, y)
 return line,
# Makes an animation by repeatedly calling a function func
# frames can be a generator, an iterable, or a number of frames.
# interval draws a new frame every interval milliseconds.
# blit=True means only re-draw the parts that have changed.
# 在这里设置一个200帧的动画,每帧之间间隔20毫秒
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() # plt.show() 会一直循环播放动画

결과:

애니메이션을 mp4 형식의 비디오 파일로 저장하려면 먼저 FFmpeg를 설치해야 합니다. FFmpeg는 디지털 오디오 및 비디오를 녹음하고 변환하며 스트림으로 변환하는 데 사용할 수 있는 오픈 소스 컴퓨터 프로그램 세트입니다. LGPL 또는 GPL 라이센스를 사용하십시오. 오디오 및 비디오 녹음, 변환 및 스트리밍을 위한 완벽한 솔루션을 제공합니다.

여기에서 Windows 버전을 다운로드하세요. Windows용 FFmpeg를 다운로드하고 압축을 푼 다음 시스템 환경 변수 경로에 bin 디렉터리를 추가하세요. 예: C:ProgramFilesffmpeg-3.2.2-win64-staticbin. 그런 다음 구성이 괜찮은지 테스트합니다. ffmpeg-version

을 입력하세요. matplotlib에 대해 더 잘 이해하고 있으니 시도해 볼 수 있습니다.

관련 권장 사항:

python matplotlib 좌표축 설정 방법

matplotlib는 논문의 요구 사항에 맞는 그림을 그립니다.

그리기 위해 matplotlib를 사용하는 Python에 대한 자세한 설명

위 내용은 matplotlib를 통한 Python 간단한 그리기 애니메이션 예제의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.