1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        用Python繪制超酷的gif動圖,驚艷了所有人

        共 1353字,需瀏覽 3分鐘

         ·

        2022-05-17 04:06

        在之前的一篇文章當(dāng)中,小編當(dāng)時分享了如何用Python當(dāng)中的gif模塊來制作gif格式的圖表,
        厲害了,用Python繪制動態(tài)可視化圖表,并保存成gif格式
        今天小編再給大家來介紹一種制作gif格式圖表的新方法,調(diào)用的是matplotlib的相關(guān)模塊,其中的步驟與方法也是相當(dāng)?shù)睾唵我锥?/section>

        下載和導(dǎo)入數(shù)據(jù)庫

        我們這次用到的數(shù)據(jù)集是bokeh模塊自帶的數(shù)據(jù)集,通過下面這一行代碼直接就可以下載

        import?bokeh
        bokeh.sampledata.download()

        然后導(dǎo)入后面要用到的數(shù)據(jù)集,我們挑選的是指定國家的1950年至今不同年齡階段的人口所占比重的數(shù)據(jù)

        from?bokeh.sampledata.population?import?data
        import?numpy?as?np

        data?=?filter_loc('United?States?of?America')
        data.head()

        output

        先繪制若干張靜態(tài)的圖表

        我們可以先繪制若干張靜態(tài)的圖表,然后將這幾張圖表合成一張gif格式的動圖即可,代碼如下

        import?seaborn?as?sns
        import?matplotlib.pyplot?as?plt
        import?matplotlib.patheffects?as?fx

        #?繪制圖表的函數(shù)
        def?make_plot(year):
        ????
        ????#?根據(jù)年份來篩選出數(shù)據(jù)
        ????df?=?data[data.Year?==?year]
        ????????
        ????#?制作圖表
        ????fig,?(ax1,?ax2)?=?plt.subplots(1,?2,?sharey?=?True)
        ????ax1.invert_xaxis()
        ????fig.subplots_adjust(wspace?=?0)?
        ????
        ????ax1.barh(df[df.Sex?==?'Male'].AgeGrp,?df[df.Sex?==?'Male'].percent,?label?=?'Male')
        ????ax2.barh(df[df.Sex?==?'Female'].AgeGrp,?df[df.Sex?==?'Female'].percent,?label?=?'Female',?color?=?'C1')
        ????
        ????country?=?df.Location.iloc[0]
        ????if?country?==?'United?States?of?America':?country?==?'US'
        ????????
        ????fig.suptitle(f'......')
        ????fig.supxlabel('......')
        ????fig.legend(bbox_to_anchor?=?(0.9,?0.88),?loc?=?'upper?right')
        ????ax1.set_ylabel('Age?Groups')
        ????
        ????return?fig

        我們自定義了一個繪制圖表的函數(shù),其中的參數(shù)是年份,邏輯很簡單,我們是想根據(jù)年份來篩選出數(shù)據(jù),然后根據(jù)篩選出的數(shù)據(jù)來繪制圖表,每一年的圖表不盡相同

        years?=?[i?for?i?in?set(data.Year)?if?i?years.sort()

        for?year?in?years:
        ????fig?=?make_plot(year)
        ????fig.savefig(f'{year}.jpeg',bbox_inches?=?'tight')

        output

        這樣我們就生成了若干張靜態(tài)的圖表,然后集合成gif格式的圖表幾個,代碼如下

        import?matplotlib.animation?as?animation
        fig,?ax?=?plt.subplots()
        ims?=?[]

        for?year?in?years:
        ????im?=?ax.imshow(plt.imread(f'{year}.jpeg'),?animated?=?True)
        ????ims.append([im])

        ani?=?animation.ArtistAnimation(fig,?ims,?interval=600)
        ani.save('us_population.gif')

        output

        還有另外一種思路

        可能看到這兒,有人會覺得上面提到的方法稍顯麻煩,畢竟我們需要先生成數(shù)十張靜態(tài)的圖表,要是電腦的磁盤空間有點緊張的話,或者還沒有這樣的一個地方來存放這數(shù)十張的圖表。于是乎就會疑問道,是不是可以一步到位的來。
        當(dāng)然也是可以的,例如我們打算繪制1950年到2020年不同年齡階段的人口比例分布圖,首先第一步在于我們先要繪制1950年,也就是起始年,該年不同年齡階段的人口比例分布圖,代碼如下

        fig,?(ax1,?ax2)?=?plt.subplots(1,?2,?sharey?=?True)
        ???
        df?=?data[data.Year?==?1955]

        y_pos?=?[i?for?i?in?range(len(df[df.Sex?==?'Male']))]
        male?=?ax1.barh(y_pos,?df[df.Sex?==?'Male'].percent,?label?=?'Male',
        ???????????????tick_label?=?df[df.Sex?==?'Male'].AgeGrp)
        female?=?ax2.barh(y_pos,?df[df.Sex?==?'Female'].percent,?label?=?'Female',?
        ??????????????????color?=?'C1',?tick_label?=?df[df.Sex?==?'Male'].AgeGrp)

        ax1.invert_xaxis()
        fig.suptitle('.......')
        fig.supxlabel('.......?(%)')
        fig.legend(bbox_to_anchor?=?(0.9,?0.88),?loc?=?'upper?right')
        ax1.set_ylabel('Age?Groups')

        output

        然后我們自定義一個繪制圖表的函數(shù),其中參數(shù)為年份,目的在于通過年份來篩選出相對應(yīng)的數(shù)據(jù)并且繪制出相對應(yīng)的圖表

        def?run(year):
        ????#?通過年份來篩選出數(shù)據(jù)
        ????df?=?data[data.Year?==?year]
        ????#?針對不同地性別來繪制
        ????total_pop?=?df.Value.sum()
        ????df['percent']?=?df.Value?/?total_pop?*?100
        ????male.remove()
        ????y_pos?=?[i?for?i?in?range(len(df[df.Sex?==?'Male']))]
        ????male.patches?=?ax1.barh(y_pos,?df[df.Sex?==?'Male'].percent,?label?=?'Male',?
        ?????????????????????color?=?'C0',?tick_label?=?df[df.Sex?==?'Male'].AgeGrp)
        ????female.remove()
        ????female.patches?=?ax2.barh(y_pos,?df[df.Sex?==?'Female'].percent,?label?=?'Female',
        ?????????????????
        ?????????????????color?=?'C1',?tick_label?=?df[df.Sex?==?'Female'].AgeGrp)

        ????text.set_text(year)
        ????return?male#,?female

        然后我們調(diào)用animation.FuncAnimation()方法,

        ani?=?animation.FuncAnimation(fig,?run,?years,?blit?=?True,?repeat?=?True,?
        ??????????????????????????????interval?=?600)
        ani.save('文件名.gif')

        output

        這樣就可以一步到位生成gif格式的圖表,避免生成數(shù)十張繁多地靜態(tài)圖片了。

        將若干張gif動圖放置在一張大圖當(dāng)中

        最后我們可以將若干張gif動圖放置在一張大的圖表當(dāng)中,代碼如下

        import?matplotlib.animation?as?animation

        #?創(chuàng)建一個新的畫布
        fig,?(ax,?ax2,?ax3)?=?plt.subplots(1,?3,?figsize?=?(10,?3))

        ims?=?[]
        for?year?in?years:
        ????im?=?ax.imshow(plt.imread(f'文件1{year}.jpeg'),?animated?=?True)
        ????im2?=?ax2.imshow(plt.imread(f'文件2{year}.jpeg'),?animated?=?True)
        ????im3?=?ax3.imshow(plt.imread(f'文件3{year}.jpeg'),?animated?=?True)
        ????ims.append([im,?im2,?im3])

        ani?=?animation.ArtistAnimation(fig,?ims,?interval=600)
        ani.save('comparison.gif')

        output




        推薦閱讀:

        入門:?最全的零基礎(chǔ)學(xué)Python的問題? |?零基礎(chǔ)學(xué)了8個月的Python??|?實戰(zhàn)項目?|學(xué)Python就是這條捷徑


        干貨:爬取豆瓣短評,電影《后來的我們》?|?38年NBA最佳球員分析?|? ?從萬眾期待到口碑撲街!唐探3令人失望? |?笑看新倚天屠龍記?|?燈謎答題王?|用Python做個海量小姐姐素描圖?|碟中諜這么火,我用機器學(xué)習(xí)做個迷你推薦系統(tǒng)電影


        趣味:彈球游戲? |?九宮格? |?漂亮的花?|?兩百行Python《天天酷跑》游戲!


        AI:?會做詩的機器人?|?給圖片上色?|?預(yù)測收入?|?碟中諜這么火,我用機器學(xué)習(xí)做個迷你推薦系統(tǒng)電影


        小工具:?Pdf轉(zhuǎn)Word,輕松搞定表格和水?。?/a>?|?一鍵把html網(wǎng)頁保存為pdf!|??再見PDF提取收費!?|?用90行代碼打造最強PDF轉(zhuǎn)換器,word、PPT、excel、markdown、html一鍵轉(zhuǎn)換?|?制作一款釘釘?shù)蛢r機票提示器!?|60行代碼做了一個語音壁紙切換器天天看小姐姐!



        年度爆款文案

        點閱讀原文,看B站我的視頻!


        瀏覽 39
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            国产偷ⅴ国产偷v精品 | 国产淫语对白粗口video | 肉感大码丰满小向美奈子 | 免费观看成人毛片 | 久久ai精品| 制服丝袜影音先锋 | 色婷婷久久综合中文久久密桃Av | 日韩国产一区二区在线观看 | 婷婷六月丁香五月 | 鸡吧操逼|