データ分析——matplotlibで基本線図を描き、fill_betweenの説明

2529 ワード

慕課ネットで学んだので,後で使うためにメモしておく.
#encoding=utf-8
import numpy as np

def main():
    # line
    import matplotlib.pyplot as plt
    x = np.linspace(-np.pi, np.pi, 256, endpoint=True) # -pi pi   256  ,        
    c, s = np.cos(x), np.sin(x)
    plt.figure(1) #       
    plt.plot(x, c, color="blue", linewidth=1.0, linestyle='-', label="COS", alpha=0.5)
    plt.plot(x, s, "r*", label="SIN") # r:red, *:   
    plt.title("Cos & Sin")

    #           ,           ,        
    ax = plt.gca() #       #spines      
    ax.spines["right"].set_color("none") #      
    ax.spines["top"].set_color("none")  #      
    ax.spines["left"].set_position(("data", 0)) #        
    ax.spines["bottom"].set_position(("data", 0))
    ax.xaxis.set_ticks_position("bottom") #       ,                  
    ax.yaxis.set_ticks_position("left") #       
    #     ,    ,            ,      
    plt.xticks([-np.pi, -np.pi / 2.0, np.pi / 2.0, np.pi],
               [r'$-\pi$', r'$-\pi/2$', r'$+\pi/2$', r'$+\pi$'])
    plt.yticks(np.linspace(-1, 1, 5, endpoint=True)) #    y      
    for label in ax.get_xticklabels() + ax.get_yticklabels(): #               
        label.set_fontsize(16)
        #   label         face:    ,edge:   ,alpha:   
        label.set_bbox(dict(facecolor="purple", edgecolor="None", alpha=0.2))
    plt.legend(loc="upper left") #     ,loc    
    plt.grid() #    
    # plt.axis([-1, 1, -0.5, 1]) # [-1, 1]       ,[-0.5,1]       
    plt.fill_between(x, np.abs(x)<0.5, c, c>0.5, color="green", alpha=0.25) #          
    t = 1
    plt.plot([t, t], [0, np.cos(t)], 'y', linewidth=3, linestyle='--') #    
    plt.annotate("cos(1)", xy=(t, np.cos(1)), xycoords="data", xytext=(+10, +30),
        textcoords="offset points", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=0.2"))
    # xy       , xytext    ,textcoords         ,connectionstyle     0.2
    plt.show()

if __name__ == "__main__":
    main()

fill_between()は2本の線間領域pltを充填する.fill_between(x,y 1,y 2=0,where=None,interpolate=False,step=None,hold=None,data=None,**kwargs)x-array(length N)定義曲線のx座標y 1-array(length N)or scalar定義第1曲線のy座標y 2-array(length N)or scalarar定義第2曲線のy座標where-array of bool(length N),optional,default:None
y 1からy 2までの水平領域が埋め込まれています