Python | Matplotlib


♟ Matplotlib

  • のグラフィックを描画するためのPythonライブラリ
  • import matplotlib.pyplot as plt
    
    x = [i for i in range(1, 6)]
    y = [i for i in range(1, 6)]
    
    plt.plot(x, y)
    plt.title("First Plot")
    plt.xlabel("x")
    plt.ylabel("y")

    オブジェクトベースのスタイルでグラフィックを描画する🥊

  • object-oriented interface
    👉 図は図画紙全体を示す
    👉 axは
  • でグラフを描くことができます
    import matplotlib.pyplot as plt
    
    x = [i for i in range(1, 6)]
    y = [i for i in range(1, 6)]
    
    fig, ax = plt.subplots()
    ax.plot(x, y)
    ax.set_title('First plot")
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    
    fig.set_dpi(300)  
    # dot per inch의 약자(그래프가 크게 저장됨)
    # 저화질로 저장시 숫자를 낮추면 됨
    
    fig.savefig("first_plot.png")  # 현재 디렉토리에 저장됨

    複数の図形を描画

    # linspace(시작, 끝, 구간)
    x = np.linspace(0, np.pi * 4, 100)
    # 2 : 세로 축으로 0, 1 두 개의 데이터를 갖게 됨
    fig, axes = plt.subplots(2, 1)
    axes[0].plot(x, np.sin(x))  # 위의 그래프
    axes[1].plot(x, np.cos(x))  # 아래 그래프

    Matplotlibのグラフィック🚣‍♀️


    1. Line plot
    fig, ax = plt.subplots()
    x = np.arange(15)
    y = x ** 2
    ax.plot(
    	x, y,
        linestyle=":",
        marker="*",
        color="#524FA1"
    )
    ⚡ linestyle
    ax.plot(x, y, linestyle="-")  # solid
    ax.plot(x, y, linestyle="--")  # dashed
    ax.plot(x, y, linestyle="-.")  # dashdot
    ax.plot(x, y, linestyle=":")  # dotted

    ⚡ Marker
    ax.plot(x, x, marker=".")  
    ax.plot(x, x+2, marker="o")  
    ax.plot(x, x+4, marker="v")  
    ax.plot(x, x+6, marker="s") 
    ax.plot(x, x+8, marker="*")  

    2. Scatter plot
  • 区画の3番目の因子に「marker」値を与えて変更する.
  • fig, ax = plt.subplots()
    x = np.arange(10)
    y = x ** 2
    ax.plot(
    	x, y,
        "o",
        markersize=15,
        markerfacecolor='white',
        markeredgecolor='blue'
    )
  • 各点の異なる表現:
  • fig, ax = plt.subplots()
    x = np.random.randn(50)
    x = np.random.randn(50)
    colors = np.random.randint(0, 100, 50)  # marker가 전부 다른 색을 갖게 해준다.
    sizes = 500 * np.pi * np.random.randn(50) ** 2
    ax.scatter(x, y, c=colors, s=sizes, alpha=0.3)  # alpha는 투명도

    3. Bar plot
    x = np.arange(10)
    fig, ax = plt.subplots(figsize=(12, 4))  # 가로 12, 세로 4
    ax.bar(x, x**2)
    累積
  • データプロット(累積プロット)
  • x = np.random.rand(3)
    y = np.random.rand(3)
    z = np.random.rand(3)
    data = [x, y, z]
    
    fig.ax = plt.subplots()
    x_ax = np.arange(3)
    
    for i in x_ax:
      # bottom을 지정해서 해당 지점부터 다시 데이터를 쌓아 올린다.
      ax.bar(x_ax, data[i], bottom=np.sum(data[:i], axis=0))
    ax.set_xticks(x_ax)
    ax.set_xticklabels(['A', 'B', 'C'])
    4. Histogram
    fig, ax = plt.subplots()
    data = np.random.randn(1000)
    ax.hist(data, bins=50)  # 막대기가 50개 생김

    軸の境界を調整するには

  • 図の可視点
  • を指定する
    x = np.linspace(0, 10, 1000)  # 0~10 사이의 1000개 데이터
    fig, ax = plt.subplots()
    ax.plot(x, np.sin(x))
    ax.set_xlim(-2, 12)  # x축이 시작하고 끝나는 지점 설정
    ax.set_ylim(-1.5, 1.5)  # y축이 시작하고 끝나는 지점 설정

    凡例

    fig, ax = plt.subplots()
    ax.plot(x, x, label='y=x')
    ax.plot(x, x**2, label='y=x^2')
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.legend(
    	loc='upper right',  # 위치 : lower, center도 있음
    	shadow=True,
        fancybox=True,  # 모서리 둥글게
        borderpad=2  # 박스의 padding 같은 것
    )

    Matplotlib with pandas 🏋️‍♂️

  • パンダのデータフレーム
  • を描画
    fig, ax = plt.subplots()
    ax.plot(df['order'], df['height(cm)'], label='height')
    ax.set_xlabel('order')
    ax.set_ylabel('height(cm)')
    
    🐧 この文章はEllis AI課程の「実戦データ分析」課程に基づいて作成された.