博客專欄

        EEPW首頁 > 博客 > 如何讓 Matplotlib、Seaborn 數據圖動起來?

        如何讓 Matplotlib、Seaborn 數據圖動起來?

        發布人:AI科技大本營 時間:2022-05-15 來源:工程師 發布文章

        作者 | pythonic生物人

        來源丨pythonic生物人

        本文介紹如何讓Matplotlib、Seaborn的靜態數據圖動起來,變得栩栩如生。


        Matplotlib

        效果圖

        圖片

        主要使用matplotlib.animation.FuncAnimation,上核心代碼:

        # 定義靜態繪圖函數
        def draw_barchart(year):
            dff = df[df['year'].eq(year)].sort_values(by='value',
                                                      ascending=True).tail(10)
            ax.clear()
            ax.barh(dff['name'],
                    dff['value'],
                    color=[colors[group_lk[x]] for x in dff['name']])
            dx = dff['value'].max() / 200
            for i, (value, name) in enumerate(zip(dff['value'], dff['name'])):
                ax.text(value - dx,
                        i,
                        name,
                        size=14,
                        weight=600,
                        ha='right',
                        va='bottom')
                ax.text(value - dx,
                        i - .25,
                        group_lk[name],
                        size=10,
                        color='#444444',
                        ha='right',
                        va='baseline')
                ax.text(value + dx,
                        i,
                        f'{value:,.0f}',
                        size=14,
                        ha='left',
                        va='center')
            # 注釋文本
            ax.text(1,
                    0.4,
                    year,
                    transform=ax.transAxes,
                    color='#777777',
                    size=46,
                    ha='right',
                    weight=800)
            ax.text(0,
                    1.06,
                    '單位 (每1000)',
                    transform=ax.transAxes,
                    size=12,
                    color='#777777')
            ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
            ax.xaxis.set_ticks_position('top')
            ax.tick_params(axis='x', colors='#777777', labelsize=12)
            ax.set_yticks([])
            ax.margins(00.01)
            ax.grid(which='major', axis='x', linestyle='-')
            ax.set_axisbelow(True)
            ax.text(0,
                    1.12,
                    '1500~2018年世界人口最多城市',
                    transform=ax.transAxes,
                    size=24,
                    weight=600,
                    ha='left')
            
            plt.box(False)


        # 調用matplotlib.animation.FuncAnimation讓靜態圖動起來
        animator = animation.FuncAnimation(fig,
                                           draw_barchart,
                                           frames=range(19682019))
        # Jupyter Notebook里展示動圖animation
        HTML(animator.to_jshtml())

        在繪圖數據部分改自己的數據既可為所欲為的使用了~


        Seaborn

        效果圖

        圖片

        代碼

        import matplotlib.pyplot as plt
        from matplotlib.animation import FuncAnimation
        import seaborn as sns
        import numpy as np
        import palettable


        def get_data(i=0):
            x, y = np.random.normal(loc=i, scale=3, size=(2260))
            return x, y
        x, y = get_data()


        g = sns.JointGrid(x=x, y=y, size=4)
        g.fig.set_size_inches(108)
        lim = (-1010)


        def prep_axes(g, xlim, ylim):
            g.ax_joint.clear()
            g.ax_joint.set_xlim(xlim)
            g.ax_joint.set_ylim(ylim)
            g.ax_marg_x.clear()
            g.ax_marg_x.set_xlim(xlim)
            g.ax_marg_y.clear()
            g.ax_marg_y.set_ylim(ylim)
            plt.setp(g.ax_marg_x.get_xticklabels(), visible=False)
            plt.setp(g.ax_marg_y.get_yticklabels(), visible=False)
            plt.setp(g.ax_marg_x.yaxis.get_majorticklines(), visible=False)
            plt.setp(g.ax_marg_x.yaxis.get_minorticklines(), visible=False)
            plt.setp(g.ax_marg_y.xaxis.get_majorticklines(), visible=False)
            plt.setp(g.ax_marg_y.xaxis.get_minorticklines(), visible=False)
            plt.setp(g.ax_marg_x.get_yticklabels(), visible=False)
            plt.setp(g.ax_marg_y.get_xticklabels(), visible=False)


        def animate(i):
            g.x, g.y = get_data(i)
            prep_axes(g, lim, lim)
            g.plot_joint(sns.kdeplot,
                         cmap='Paired')
            g.plot_marginals(sns.kdeplot, color='blue', shade=True)


        frames = np.sin(np.linspace(02 * np.pi, 17)) * 5
        ani = matplotlib.animation.FuncAnimation(g.fig,
                                                 animate,
                                                 frames=frames,
                                                 repeat=True)
        HTML(ani.to_jshtml())

        和Matplotlib代碼類似,不過多解釋。


        *博客內容為網友個人發布,僅代表博主個人觀點,如有侵權請聯系工作人員刪除。



        關鍵詞: 算法

        相關推薦

        技術專區

        關閉
        主站蜘蛛池模板: 共和县| 新安县| 密山市| 张家界市| 柏乡县| 浦县| 石家庄市| 新丰县| 崇信县| 禄劝| 永和县| 泗洪县| 栾川县| 通化县| 富阳市| 含山县| 钦州市| 德化县| 海安县| 游戏| 玛沁县| 新化县| 长海县| 柞水县| 邹城市| 宿迁市| 临夏市| 姜堰市| 揭西县| 秦皇岛市| 格尔木市| 嫩江县| 古丈县| 尼勒克县| 平果县| 武宣县| 长白| 湘西| 新民市| 乐清市| 阳山县|