matplotlib ノート

matplotlib.txt


"""
matplotlib ノート
"""


#==============
# import
#==============

from matplotlib import pyplot as plt

#==============
#基本
#==============

#グラフの作成、表示
# marker: o, x etc linestyle: None, -, dashed, dotted etc
# color: red, blue, green, black etc
plt.plot(x, y, label='raw data', marker = 'o', markersize = 0.5, linestyle = 'None', linewidth = 0.5, color = 'red')
plt.plot(xc, yc, label='fitted', linestyle = 'dashed')
#plt.scatter(x, y)
#plt.bar(xindex, v, width = 1.5)
plt.title(infile, fontsize = fontsize)
plt.xlabel(header[0], fontsize = fontsize)
plt.ylabel(header[1], fontsize = fontsize)
plt.legend(fontsize = fontsize)
#フォントサイズ
plt.legend(fontsize = legend_fontsize)
plt.tick_params(labelsize = fontsize)

#グラフを表示してプログラムを一時停止
plt.show()


#==============
#グラフのクリアー
#==============

#グラフ全体のクリアー (clear figure)
# clears the entire current figureをすべての軸で表示しますが、
# 他のプロットで再利用できるように、ウィンドウを開いたままにしておきます。
    figure.clf()

#グラフのクリアー (clear axis)
#clears an axis、すなわち、現在の図形内の現在アクティブな軸。それは他の軸を手つかずのままにします。
    figure.cla()
# closes a windowは、特に指定がない場合は現在のウィンドウになります。
    plt.close()

#=========================================
#複数グラフ plotcsv_mult.py
#=========================================

# figureオブジェクト取得
    fig = plt.figure(figsize = (15,7))

#縦1、横2に分割し、1番目のグラフ枠をax1に代入
    ax1 = fig.add_subplot(1, 2, 1)
# ax1 = fig.add_subplot(121)
    ax1.set_yscale('log')
#プロットしたデータのオブジェクト
    data = ax1.plot(xT, yEF, label = 'alpha')
    ax1.plot(xT, yEFapprox, label = 'alpha(approx)', linestyle = '-', linewidth = 0.5, color = 'red')
    ax1.set_xlabel("T (K)")
    ax1.set_ylabel("alpha = -mu/(kBT)")
    ax1.set_xlim([Tmin, Tmax])
    ax1.set_ylim([0.0, max(yEF)])
#フォントサイズ
    ax1.tick_params(labelsize = fontsize)
#フォントサイズを指定して凡例を表示
    ax1.legend(fontsize = legend_fontsize)
#グラフ間スペースの自動調整
    plt.tight_layout()
#グラフ間スペースの手動調整
    plt.subplots_adjust(wspace=0.4, hspace=0.6)

#グラフを表示。0.001秒スリープし、プログラムを続行
    plt.pause(0.001)

    print("Press ENTER to exit>>", end = '')
    input()


#=========================================
#3Dグラフ optimize-sd-cg2d-linesearch.py
#=========================================

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib import cm

        fig = plt.figure(figsize = (10, 5))
        ax = fig.add_subplot(1, 2, 1)
        ax2 = fig.add_subplot(1, 2, 2, projection='3d')
# surf = ax.plot_surface(xg, yg, zg, cmap=cm.coolwarm)
        surf = ax2.plot_wireframe(xg, yg, zg, rstride=2, cstride=2)
# ax.set_zlim3d(-3.01, 3.01)
# plt.colorbar(surf, shrink=0.5, aspect=10)
        ax.set_title('contour')
        contour = ax.contourf(xg, yg, zg, levels = 51, cmap = 'Spectral')
# contour = ax.contour(xg, yg, zg, levels = 51, cmap = 'Spectral')
        solve, = ax.plot([], color = 'blue', marker = 'o', linestyle = '-')
        plt.pause(0.1)

    for iter in range(nmaxiter):
#データのリストを更新
            xt.append(x0[0])
            yt.append(x0[1])
#データをセット
            solve.set_data(xt, yt)
            plt.pause(0.1)
            time.sleep(tsleep)


#=========================================
#グラフの更新 diffeq2nd_planet.py plot_realtimeupdate.py
#=========================================

    fig, ax = plt.subplots(1, 1)

    # 一度plotする、プロットデータのオブジェクトを受け取る受け取る
    lines, = ax.plot(x, y)

    while True:
        # plotデータの更新
        x.append(x[n-1] + 0.1)
        y.append(np.sin(x[n]))

        # 描画データを更新するときにplot関数を使うと
        # lineオブジェクトが増えてしまう。
        # set_data()メソッドで描画データを更新する
        lines.set_data(x, y)

        # set_data()を使うと軸とかは自動設定されない
        # x軸の範囲は適宜修正してやる必要がある.
        ax.set_xlim((min(x), max(x)))
        ax.set_ylim((min(y), max(y)))

        # plt.show() プログラムが停止する
        # plt.ion() + plt.draw() グラフウインドウが固まってプログラムが止まる
        plt.pause(0.01)


#=========================================
#グラフの更新 (グラフをクリアーして再描画)
#=========================================

    plt.clf()
    plt.title(infile, fontsize = fontsize)
    plt.xlabel(header[0], fontsize = fontsize)
    plt.ylabel('log(' + header[1] + ')', fontsize = fontsize)
    plt.plot(Vd, logId, label='raw data', marker = 'o', markersize = 0.5, linestyle = 'None')
    plt.plot(Vi, logIi, label='initial', linestyle = 'dotted')
    if ai is not None:
        Vc, Ic, logIc = CalIV(ai)
        plt.plot(Vc, logIc, label='final', linestyle = 'dashed')
#フォントサイズ
    plt.legend(fontsize = legend_fontsize)
    plt.tick_params(labelsize = fontsize)
#グラフ間スペースの自動調整
    plt.tight_layout()
    plt.pause(0.001)


#=========================================
# callback peakfit-scipy-minimize.py
#=========================================

def callback(xk):
    global xd
    global iter
    global figure, ax_fit, ax_conv
    global fitdata, convdata

    fmin = CalS2(xk)
    print("callback {}: xk={}".format(iter, xk))
    print(" fmin={}".format(fmin))
    iter += 1
    xiter.append(iter)
    yfmin.append(fmin)

    convdata[0].set_data(xiter, yfmin)
    ax_conv.set_xlim((0.0, max(xiter) + 1.0))
    ax_conv.set_ylim((min(yfmin) * 0.8, max(yfmin) * 1.2))

    yc = ycal_list(xd, xk)
    fitdata[0].set_data(xd, yc)

    plt.pause(0.2)

def main():
        figure = plt.figure(figsize = (10, 5))
        ax_fit = figure.add_subplot(1, 2, 1)
        rawdata = ax_fit.plot(xd, yd, color = 'blue', linestyle = '', linewidth = 0.5,
                            fillstyle = 'full', marker = 'x', markersize = 5)
        inidata = ax_fit.plot(xd, yini, color = 'black', linestyle = 'dashed', linewidth = 0.5)
        fitdata = ax_fit.plot([], [], color = 'red', linestyle = '-', linewidth = 0.5)

        ax_conv = figure.add_subplot(1, 2, 2)
        ax_conv.set_yscale('log')
        convdata = ax_conv.plot([], [], color = 'black', linestyle = '-', linewidth = 0.5,
                            fillstyle = 'full', marker = 'o', markersize = 5)
        plt.pause(0.001)


    res = minimize(CalS2, x0, jac=diff1, method=method, tol = tol, callback = callback,
                options = {'maxiter':maxiter, "disp":True})


#=========================================
tkinterに統合 11-leastsq-GUI-tkmatplot.py
#=========================================

import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# Canvas (right)
# figure = plt.subplots()
    figure = plt.Figure()
# figure = plt.Figure(figsize=(10, 3), dpi=100)
    canvas = FigureCanvasTkAgg(figure, master = right_frame)
    canvas.get_tk_widget().pack(side = 'bottom', expand = 1)
    canvas._tkcanvas.pack(side = 'bottom', expand = 1)
    obj['figure'] = figure
    obj['canvas'] = canvas

    figure = obj['figure']
    figure.clf()
    ax = figure.add_subplot(111)
    ax.plot(x, y, label = 'raw data', marker = 'o', linestyle = 'None')
    ax.plot(xc, yc, label = 'fitted', linestyle = 'dashed')
    ax.set_title(obj['title'].get(), fontsize = fontsize)
    ax.set_xlabel(obj['xlabel'].get(), fontsize = fontsize)
    ax.set_ylabel(obj['ylabel'].get(), fontsize = fontsize)
    ax.legend(fontsize = fontsize)
    ax.tick_params(labelsize = fontsize)
#グラフ間スペースを自動調整
    figure.tight_layout()
    canvas.draw()