小林 未知数の備忘録
Matplotlib

基本

  • 基本的な使い方

    Axesは慣れるのに時間がかかりそう
                    import matplotlib.pyplot as plt
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot([1,2],[1,2])
                    plt.show()
  • 点を打つ

                    import matplotlib.pyplot as plt
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot([1,2],[1,2],marker="o")
  • 線のスタイルを変える

                    import matplotlib.pyplot as plt
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot([1,2],[1,2],linestyle="dashed",color="tab:orange")

    dashedではなくNoneとすれば線が消える
  • 線の太さ、点の大きさを変える

                    import matplotlib.pyplot as plt
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot([1,2],[1,2],marker="o",linewidth=3,markersize=15)
  • 軸に名前を付ける

                    import matplotlib.pyplot as plt
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot([1,2],[0,24])
                    ax.set_xlabel("day",labelpad=5)
                    ax.set_ylabel("hour",labelpad=10)

    labelpadは軸からどれだけ離すか(省略可)
  • サイズと範囲指定

                    import matplotlib.pyplot as plt
                    fig=plt.figure(figsize=(10,4))
                    ax=fig.add_subplot(111)
                    ax.plot([1,2],[1,2])
                    ax.set_xlim(1,5)
                    ax.set_ylim(0,3)

  • 凡例を付ける

                    import matplotlib.pyplot as plt
                    import numpy as np
                    t=np.linspace(0,10,100)
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot(t,np.sin(t),label="sin(t)")
                    ax.plot(t,np.cos(t),label="cos(t)")
                    ax.legend()

  • 任意の場所に文字を入れる

    transform=ax.transAxesを付けると、グラフ上の座標ではなく、グラフ枠に対する座標を指定できる。
                    import matplotlib.pyplot as plt
                    import numpy as np
                    t=np.linspace(0,10,100)
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot(t,np.sin(t),label="sin(t)")
                    ax.text(0.02,0.95,"(a)",transform=ax.transAxes)
                    ax.set_xlabel("t")

  • 左右の軸を使う

                    import matplotlib.pyplot as plt
                    import numpy as np
                    t=np.linspace(0,10,100)
                    fig=plt.figure()
                    ax1=fig.add_subplot(111)
                    ax1.plot(t,np.sin(t),color="tab:blue")
                    ax1.set_xlabel("t")
                    ax1.set_ylabel("sin(t)")
                    ax2=ax1.twinx()
                    ax2.plot(t,np.tan(t),color="tab:orange")
                    ax2.set_ylim(-10,10)
                    ax2.set_ylabel("tan(t)")

  • 左右の軸を使い、共通の凡例を付ける

                    import matplotlib.pyplot as plt
                    import numpy as np
                    t=np.linspace(0,10,100)
                    fig=plt.figure()
                    ax1=fig.add_subplot(111)
                    ln1=ax1.plot(t,np.sin(t),color="tab:blue",label="sin(t)")
                    ax1.set_xlabel("t")
                    ax1.set_ylabel("sin(t)")
                    ax2=ax1.twinx()
                    ln2=ax2.plot(t,np.tan(t),color="tab:orange",label="tan(t)")
                    ax2.set_ylim(-10,10)
                    ax2.set_ylabel("tan(t)")
                    ln=ln1+ln2
                    lab=[l.get_label() for l in ln]
                    ax2.legend(ln,lab,loc=4)

    loc=1 (右上), 2 (左上), 3 (左下), 4 (右下)
  • ファイルの保存

    dvipngとcm-superをインストールしておく
                    sudo apt update
                    sudo apt install cm-super
                    sudo apt install dvipng
                  plt.savefig("hoge.pdf")
    余白を最小にするには
                    plt.savefig("hoge.pdf",bbox_inches="tight",pad_inches=0)
    pad_inchesは0にするとpngなどのときにぎりぎり切れることがある。その場合小さい値を入れる。透明を背景にするにはtransparent=Trueを入れる。

文字関連

  • LaTeX仕様

                    import matplotlib.pyplot as plt
                    import numpy as np
                    t=np.linspace(0,5,100)
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot(t,np.exp(-t)*np.sin(t))
                    ax.set_title(r"$x=e^{-t} \sin 5t$")
                    ax.set_xlabel(r"$t$")
                    ax.set_ylabel(r"$x$")

  • 完全LaTeX仕様

                    import matplotlib as mpl
                    import matplotlib.pyplot as plt
                    import numpy as np
                    t=np.linspace(0,5,100)
                    mpl.rc("text",usetex=True)
                    mpl.rcParams["text.latex.preamble"]= r"\usepackage{cmbright,amsmath,amssymb}" 
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot(t,np.exp(-t)*np.sin(t))
                    ax.set_title(r"$x=e^{-t} \sin 5t$")
                    ax.set_xlabel(r"$t$")
                    ax.set_ylabel(r"$x$")

  • フォントサイズの変更

                    import matplotlib as mpl
                    import matplotlib.pyplot as plt
                    import numpy as np
                    t=np.linspace(0,5,100)
                    mpl.rcParams["font.size"]=16
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot(t,np.exp(-t)*np.sin(t))
                    ax.set_title(r"$x=e^{-t} \sin 5t$")
                    ax.set_xlabel(r"$t$")
                    ax.set_ylabel(r"$x$")

  • 日本語を使用する

                    import matplotlib as mpl
                    import matplotlib.pyplot as plt
                    import numpy as np
                    t=np.linspace(0,5,100)
                    mpl.rcParams["font.family"]="IPAexGochic"
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot(t,np.exp(-t)*np.sin(t))
                    ax.set_title(r"$x=e^{-t} \sin 5t$のグラフ")
                    ax.set_xlabel("時間")
                    ax.set_ylabel("減衰振動")

  • LaTeX仕様で日本語を使用する

                    import matplotlib as mpl
                    import matplotlib.pyplot as plt
                    import numpy as np
                    t=np.linspace(0,5,100)
                    mpl.rc("text",usetex=True)
                    mpl.rcParams["text.latex.preamble"]= r"\usepackage{cmbright,amsmath,amssymb}" r"\usepackage[whole]{bxcjkjatype}" 
                    fig=plt.figure()
                    ax=fig.add_subplot(111)
                    ax.plot(t,np.exp(-t)*np.sin(t))
                    ax.set_title(r"$x=e^{-t} \sin 5t$のグラフ")
                    ax.set_xlabel("時間")
                    ax.set_ylabel("減衰振動")

データ読み込み

  • バイナリファイルの読み込み

                    import numpy as np
                    f=open("hoge.bin")
                    data=np.fromfile(f,dtype="f8",sep="")
  • アスキーファイルの読み込み

    アスキーファイルはnumpy.loadtxtやnumpy.genfromtxtよりもpandas.read_tableの方が割と賢く読み込んでくれる気がする。必要であればその後、numpy.arrayで配列に。
                    import numpy as np
                    import pandas as pd
                    data=pd.read_table("hoge.dat",sep="\s+",header=None)
                    data=np.array(data)