복붙노트

[PYTHON] Jupyter의 인라인 애니메이션

PYTHON

Jupyter의 인라인 애니메이션

파이썬 애니메이션 스크립트 (matplotlib의 funcAnimation 사용)가 있습니다.이 스크립트는 Spyder에서 실행되지만 Jupyter에서는 실행되지 않습니다. 나는 "% matplotlib inline"을 추가하고 matplotlib 백엔드를 "Qt4agg"로 변경하는 등의 다양한 제안을 시도했지만 성공하지 못했습니다. 또한 몇 가지 예제 애니메이션 (Jupyter 자습서)을 실행 해 보았습니다. 때로는 오류 메시지가 표시되고 때로는 플롯이 나타나지만 애니메이션으로 표시되지 않는 경우가 있습니다. 덧붙여서, 나는 "% matplotlib inline"을 사용하여 pyplot.plot ()을 사용했다.

누구든지 funcAnimation을 사용하는 간단한 인라인 애니메이션 예제를 가진 Jupyter 노트북을 알고 있습니까? 도움에 미리 감사드립니다!

[참고 : 저는 Windows 7입니다]

해결법

  1. ==============================

    1.'인라인'은 플롯이 png 그래픽으로 표시됨을 의미합니다. 그 png 이미지는 움직일 수 없습니다. 원칙적으로 png 이미지를 연속적으로 교체하여 애니메이션을 만들 수는 있지만 이는 바람직하지 않습니다.

    '인라인'은 플롯이 png 그래픽으로 표시됨을 의미합니다. 그 png 이미지는 움직일 수 없습니다. 원칙적으로 png 이미지를 연속적으로 교체하여 애니메이션을 만들 수는 있지만 이는 바람직하지 않습니다.

    해결 방법은 matplotlib 그림 자체를 렌더링 할 때 FuncAnimation과 완벽하게 호환되는 노트북 백엔드를 사용하는 것입니다.

    %matplotlib notebook
    

    matplotlib 2.1 on부터 JavaScript를 사용하여 애니메이션을 만들 수 있습니다. 이것은 비디오 코덱이 필요 없다는 점을 제외하면 ani.to_html5 () 솔루션과 유사합니다.

    from IPython.display import HTML
    HTML(ani.to_jshtml())
    

    몇 가지 완전한 예 :

    import matplotlib.pyplot as plt
    import matplotlib.animation
    import numpy as np
    
    t = np.linspace(0,2*np.pi)
    x = np.sin(t)
    
    fig, ax = plt.subplots()
    ax.axis([0,2*np.pi,-1,1])
    l, = ax.plot([],[])
    
    def animate(i):
        l.set_data(t[:i], x[:i])
    
    ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
    
    from IPython.display import HTML
    HTML(ani.to_jshtml())
    

    또는 jsanimation을 애니메이션 표시를위한 기본값으로 만들고,

    plt.rcParams["animation.html"] = "jshtml"
    

    그런 다음 애니메이션을 얻으려는 애니를 간단하게 말하십시오.

    전체 개요는이 답변을 참조하십시오.

  2. ==============================

    2.이 자습서에는 http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/의 간단한 예제가 있습니다.

    이 자습서에는 http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/의 간단한 예제가 있습니다.

    위의 튜토리얼을 요약하면, 기본적으로 다음과 같은 것이 필요하다.

    from matplotlib import animation
    from IPython.display import HTML
    
    # <insert animation setup code here>
    
    anim = animation.FuncAnimation()  # With arguments of course!
    HTML(anim.to_html5_video())
    

    하나...

    나는 그 일을하는 데 많은 어려움을 겪었습니다. 근본적으로, 문제는 위에서 ffmpeg와 x264 코덱을 백그라운드에서 사용하지만, 내 컴퓨터에서 제대로 구성되지 않았다는 것입니다. 해결책은이를 제거하고 올바른 구성으로 소스에서 다시 빌드하는 것입니다. 자세한 내용은 Andrew Heusser의 답변 : ipython (jupyter) 노트북의 애니메이션 - ValueError : 닫힌 파일에 대한 I / O 작업

    따라서 먼저 to_html5_video 솔루션을 시도해보십시오. 작동하지 않는 경우 ffmpeg 및 x264의 제거 / 재구성을 시도해보십시오.

  3. ==============================

    3.다음은 공식 예제를 비롯한 여러 소스에서 나온 답변입니다. Jupyter와 Python의 최신 버전으로 테스트했습니다.

    다음은 공식 예제를 비롯한 여러 소스에서 나온 답변입니다. Jupyter와 Python의 최신 버전으로 테스트했습니다.

    
        import numpy as np
        import matplotlib.pyplot as plt
        import matplotlib.animation as animation
        from IPython.display import HTML
    
        #=========================================
        # Create Fake Images using Numpy 
        # You don't need this in your code as you have your own imageList.
        # This is used as an example.
    
        imageList = []
        x = np.linspace(0, 2 * np.pi, 120)
        y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
        for i in range(60):
            x += np.pi / 15.
            y += np.pi / 20.
            imageList.append(np.sin(x) + np.cos(y))
    
        #=========================================
        # Animate Fake Images (in Jupyter)
    
        def getImageFromList(x):
            return imageList[x]
    
        fig = plt.figure(figsize=(10, 10))
        ims = []
        for i in range(len(imageList)):
            im = plt.imshow(getImageFromList(i), animated=True)
            ims.append([im])
    
        ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000)
        plt.close()
    
        # Show the animation
        HTML(ani.to_html5_video())
    
        #=========================================
        # Save animation as video (if required)
        # ani.save('dynamic_images.mp4')
    
    
  4. from https://stackoverflow.com/questions/43445103/inline-animations-in-jupyter by cc-by-sa and MIT license