matplotlib動態繪圖


package

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from mpl_toolkits.mplot3d import Axes3D

Process

在matplotlib中畫圖有兩種顯示模式:

(1)阻塞模式,即必須利用plt.show()顯示圖片,且圖片關閉之前代碼將阻塞在該行。

(2)交互模式,即plt.plot()后立馬顯示圖片,且不阻塞代碼的繼續運行。

Matplotlib中默認是使用阻塞模式。看一下這里用到的matplotlib中的幾個函數:

plt.ion():打開交互模式
plt.ioff():關閉交互模式
plt.clf():清除當前的Figure對象
plt.cla():清除當前的Axes對象
plt.pause():暫停功能

若只利用plt.show()繪圖時,程序會停止執行之后的程序,所以通過plt.ion()開啟畫圖窗口進入交互模式,利用程序plt.plot()實時繪圖,中間會有暫停繪制完成后,再利用plt.ioff()退出交互模式,並使用plt.show()顯示最后的圖片數據,若最后不加入plt.show()會閃退

解決中文亂碼問題

myfont = fm.FontProperties(fname="/Library/Fonts/Songti.ttc", size=14)
matplotlib.rcParams["axes.unicode_minus"] = False

simple_plot()

two curve are fitting

def simple_plot():
    """
    simple plot
    """
    # 生成畫布
    plt.figure(figsize=(8, 6), dpi=80)

    # 打開交互模式
    plt.ion()

    # 循環
    for index in range(100):
        # 清除原有圖像
        plt.cla()

        # 設定標題等
        plt.title("動態曲線圖", fontproperties=myfont)
        plt.grid(True)

        # 生成測試數據
        x = np.linspace(-np.pi + 0.1*index, np.pi+0.1*index, 256, endpoint=True)
        y_cos, y_sin = np.cos(x), np.sin(x)

        # 設置X軸
        plt.xlabel("X軸", fontproperties=myfont)
        plt.xlim(-4 + 0.1*index, 4 + 0.1*index)
        plt.xticks(np.linspace(-4 + 0.1*index, 4+0.1*index, 9, endpoint=True))

        # 設置Y軸
        plt.ylabel("Y軸", fontproperties=myfont)
        plt.ylim(-1.0, 1.0)
        plt.yticks(np.linspace(-1, 1, 9, endpoint=True))

        # 畫兩條曲線
        plt.plot(x, y_cos, "b--", linewidth=2.0, label="cos示例")
        plt.plot(x, y_sin, "g-", linewidth=2.0, label="sin示例")

        # 設置圖例位置,loc可以為[upper, lower, left, right, center]
        plt.legend(loc="upper left", prop=myfont, shadow=True)

        # 暫停
        plt.pause(0.1)

    # 關閉交互模式
    plt.ioff()

    # 圖形顯示
    plt.show()
    return
# simple_plot()

scatter_plot()

def scatter_plot():
    """
    scatter plot
    """
    # 打開交互模式
    plt.ion()

    # 循環
    for index in range(50):
        # 清除原有圖像
        # plt.cla()

        # 設定標題等
        plt.title("動態散點圖", fontproperties=myfont)
        plt.grid(True)

        # 生成測試數據
        point_count = 5
        x_index = np.random.random(point_count)
        y_index = np.random.random(point_count)

        # 設置相關參數
        color_list = np.random.random(point_count)
        scale_list = np.random.random(point_count) * 100

        # 畫散點圖
        plt.scatter(x_index, y_index, s=scale_list, c=color_list, marker="o")

        # 暫停
        plt.pause(0.2)

    # 關閉交互模式
    plt.ioff()

    # 顯示圖形
    plt.show()
    return
# scatter_plot()

three_dimension_scatter()

def three_dimension_scatter():
    """
    3d scatter plot
    """
    # 生成畫布
    fig = plt.figure()

    # 打開交互模式
    plt.ion()

    # 循環
    for index in range(50):
        # 清除原有圖像
        fig.clf()

        # 設定標題等
        fig.suptitle("三維動態散點圖", fontproperties=myfont)

        # 生成測試數據
        point_count = 100
        x = np.random.random(point_count)
        y = np.random.random(point_count)
        z = np.random.random(point_count)
        color = np.random.random(point_count)
        scale = np.random.random(point_count) * 100

        # 生成畫布
        ax = fig.add_subplot(111, projection="3d")

        # 畫三維散點圖
        ax.scatter(x, y, z, s=scale, c=color, marker=".")

        # 設置坐標軸圖標
        ax.set_xlabel("X Label")
        ax.set_ylabel("Y Label")
        ax.set_zlabel("Z Label")

        # 設置坐標軸范圍
        ax.set_xlim(0, 1)
        ax.set_ylim(0, 1)
        ax.set_zlim(0, 1)

        # 暫停
        plt.pause(0.2)

    # 關閉交互模式
    plt.ioff()

    # 圖形顯示
    plt.show()
    return
# three_dimension_scatter()

Jupyter notebook

有些時候matplotlib 的繪圖沒法顯示在notebook中,或者顯示不了。這與backend有關。

首先啟動你的notebook,輸入

%pylab
查看你的matplotlib后端,我的輸出為:

Qt5Agg
這是后端的渲染方式,使用的是qt5渲染。激活方式為在繪圖之前插入代碼段:

%matplotlib qt5
這樣就能顯示出圖,但是是顯示在notebook之外的,如果我使用%matplotlib inline,圖的顯示並不正常。如果你輸出的后端為其他類型,建議查看下面的資料,直接輸入對應的繪圖激活方式。

matplotlib 常用backend

Reference: jupyter notebook matplotlib繪制動態圖並顯示在notebook中


免責聲明!

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



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