Python 繪圖與可視化 matplotlib 制作Gif動圖


參考鏈接:https://blog.csdn.net/theonegis/article/details/51037850

補充:

  若是有多個操作對象,animate里不返回也是可以的;

#縮進沒有嚴格
def animate(fi):
        # bars=[]
        for i in range(algorithm_num):
            if len(frames_names[algorithm_list[i].__name__])>fi:
                
                for rect,yi in zip(frames_names['bar%s'%algorithm_list[i].__name__],frames_names[algorithm_list[i].__name__][fi]):
                    rect.set_height(yi.value)
                    rect.set_color(yi.color)
    anim=animation.FuncAnimation(fig,animate,frames=max(list(map(int,list(frame_count.values())) )),interval=frame_interval,repeat=True)

  

官方文檔:https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.animation.FuncAnimation.html

  我們可以使用Matplotlib的animation類的FuncAnimation()方法來制作動畫,只需要提供一個動態更新數據的函數

  需要注意的是,這個函數需要以元組的形式返回一個需要在下一次繪圖中更新的數據

一個擁有詳細解釋的實例的鏈接:http://codingpy.com/article/drawing-gifs-with-matplotlib

 

有兩點需要注意

  1. 圖里的散點部分是不變的;變的是直線
  2. X 軸的標題每一幀都在變化
import numpy as np
import matplotlib as plt
from matplotlib import animation

plt.fig,ax=plt.subplots()
plt.fig.set_tight_layout(True)#tight:緊的;layout:布局
    #DPI:每英寸的點數
    #獲取圖片的分辨率和尺寸
    #在保存圖片時,還需要另外指明圖片的DPI
print('圖片的分辨率尺寸是{0}DPI,size in inches is {1}'.format(plt.fig.get_dpi(),plt.fig.get_size_inches()))#inches:英寸

    #畫出一個維持不變的散點圖和一開始的那條直線
    #困難的問題從約定俗成的方法去解決,不如先不管多么復雜的圖像,第一步就是創建點的集合
X=np.arange(0,20,0.1)
ax.scatter(X,X+np.random.normal(0,3.0,len(X)))#這種方法很好啊
line,=plt.plot(X,X-0.5,'r-',linewidth=2)
plt.title('Interesting Graph',fontsize='large',fontweight='bold',verticalalignment='center')#設置標題位置不起作用
def update(i):
    label='timestep{0}'.format(i)
    print(label)
    #更新直線和X軸,使用一個新的X軸的標簽
    #以元組的形式返回在這一幀需要被更新的物體
    line.set_ydata(X-5+i)
    ax.set_label(label)
    return ax,line

if __name__=='__main__':
    #FuncAnimation會在每一幀都調用update函數
    #在這里設置一個10幀的動畫,每幀之間間隔200ms
    anim=animation.FuncAnimation(plt.fig,update,frames=np.arange(0,10),interval=200)#frame:幀
    #我知道問什么這里提示figundefine了,因為前面的fig在函數中聲明的
    plt.show()

  

  

FuncAnimation方法的一些參數:

  fig:對象

  update:以元組形式返回這一幀需要被重新繪圖物體的一個函數

  frames:幀數

  interval:每幀之間的間隔,以毫秒為單位

保存

如果你想用matplotlib的save方法渲染GIF圖的話,就必須安裝ImageMagick

ageMagick是一個免費的創建、編輯、合成圖片的軟件。它可以讀取、轉換、寫入多種格式的圖片

anim.save('line.gif', dpi=80, writer='imagemagick')

  

其他的:

記得要掌握一些知識點約定俗稱的步驟,如使用matplotlib畫圖,無論多么復雜,第一步都是構造點的集合np.arange或者random.normal(),或者曲線np.linspace(),尤其是面對新的問題,這樣做就顯得特別重要

問題:

  1)無法顯示title

  2)導入seaborn包沒有用(已解決)

  

import seaborn as sns
sns.set_style('whitegrid')

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM