[Matplotlib] figure와 axes 직접 제어하는 방법

반응형
    반응형

    Matplotlib에서 figure와 axes를 직접 제어하는 방법과 간단한 사용법의 차이

    Matplotlib는 그래프를 그릴 때 2가지 방법이 있습니다. figure와 axes를 직접 제어하느냐에 따라 방법이 달라집니다. 직접 제어하면 코딩이 약간 복잡해지지만 관리, 유지보수가 편해지고 그렇지 않으면 바로 그릴 수는 있지만 그래프 갯수가 많아지고 여러가지 스타일을 부여하면 복잡한 코딩이 될 수 있습니다.

    간단한 사용법

    figure와 axes를 제어하지 않는 방법입니다. 직관적으로 그림을 그릴 수 있습니다. 서브플롯 각각을 설정해서 그래프를 그립니다.

    import matplotlib.pyplot as plt
    import numpy as np
    
    # 데이터 생성
    x = np.linspace(0, 2*np.pi, 100)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.tan(x)
    
    # 서브플롯 1: 선 그래프
    plt.subplot(2, 2, 1)
    plt.plot(x, y1, color='blue', label='sin(x)')
    plt.title('Sine Function')
    plt.legend()
    
    # 서브플롯 2: 산점도
    plt.subplot(2, 2, 2)
    plt.scatter(x, y2, color='red', label='cos(x)')
    plt.title('Scatter Plot of Cosine Function')
    plt.legend()
    
    # 서브플롯 3: 막대 그래프
    plt.subplot(2, 2, 3)
    plt.bar(x, y3, color='green', label='tan(x)')
    plt.title('Bar Plot of Tangent Function')
    plt.legend()
    
    # 서브플롯 4: 히스토그램
    plt.subplot(2, 2, 4)
    plt.hist(y1, bins=20, color='orange', alpha=0.7)
    plt.title('Histogram of Sine Function')
    
    # 그래프 출력
    plt.tight_layout()
    plt.show()

    직접 figure, axes 입력

    figure와 axes를 직접 만드는 방법입니다. 보통 plt.suplats 을 이용해서 생성합니다. 객체 지향적인 접근 방식이어서 추후에 모듈화하기가 편해집니다.

    import matplotlib.pyplot as plt
    import numpy as np
    
    # 데이터 생성
    x = np.linspace(0, 2*np.pi, 100)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.tan(x)
    
    # figure와 서브플롯 직접 생성
    fig, axes = plt.subplots(2, 2, figsize=(10, 8))  # 2행 2열의 서브플롯 생성
    
    # 각 서브플롯에 다른 유형의 그래프 그리기
    axes[0, 0].plot(x, y1, color='blue', label='sin(x)')
    axes[0, 0].set_title('Sine Function')
    axes[0, 0].legend()
    
    axes[0, 1].scatter(x, y2, color='red', label='cos(x)')
    axes[0, 1].set_title('Scatter Plot of Cosine Function')
    axes[0, 1].legend()
    
    axes[1, 0].bar(x, y3, color='green', label='tan(x)')
    axes[1, 0].set_title('Bar Plot of Tangent Function')
    axes[1, 0].legend()
    
    axes[1, 1].hist(y1, bins=20, color='orange', alpha=0.7)
    axes[1, 1].set_title('Histogram of Sine Function')
    
    # 전체 figure에 대한 제목 추가
    fig.suptitle('Different Types of Plots')
    
    # 그래프 출력
    plt.tight_layout()
    plt.show()

    직접 figure, axes 생성할 때의 장점

    직접 figure,axes를 생성하면 내가 직접 제어할 수 있어 장점이 많습니다. 제가 생각하는 장점은 이렇습니다.

    1. 그리드 크기, 서브플롯 배치, 그래프의 크기 등을 세밀하게 제어할 수 있습니다.
    2. axes를 객체로써 제어하면 matplotlib의 고급 기능을 활용할 수 있습니다.
    3. 객체 지향적인 접근 방식이기에 모듈화가 쉬워져 유지보수에 용이합니다.
    4. 내가 직접 figure, axes를 정했으니 프로젝트에서 일관된 크기와 스타일을 유지할 수 있습니다.
    5. 스타일 변경시 figure,axes만 변경하면 모든 그래프의 스타일을 변경할 수 있습니다.

    더하여, for문에 적용하기가 편해집니다.

    import matplotlib.pyplot as plt
    import numpy as np
    
    # 데이터 생성
    
    x = np.linspace(0, 2*np.pi, 100)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.tan(x)
    
    # 서브플롯을 만들기 위한 설정
    num_rows = 2
    num_cols = 2
    num_plots = num_rows * num_cols
    
    # figure 생성
    fig = plt.figure(figsize=(10, 8))
    
    # 서브플롯에 그래프 그리기
    for i in range(1, num_plots + 1):
        ax = fig.add_subplot(num_rows, num_cols, i)
        if i == 1:
            ax.plot(x, y1, color='blue')
            ax.set_title('Sine Function')
    
        elif i == 2:
            ax.plot(x, y2, color='red')
            ax.set_title('Cosine Function')
    
        elif i == 3:
            ax.plot(x, y3, color='green')
            ax.set_title('Tangent Function')
    
        elif i == 4:
            ax.scatter(x, y1, color='orange')
            ax.set_title('Scatter Plot of Sine Function')
    
    # 서브플롯 간 간격 조정
    plt.tight_layout()
    
    # 그래프 출력
    plt.show()

     

    물론 서브플롯마다 설정해주어야 하는 건 비슷할수도 있겠으나 적어도 배열을 plt.subplot(x,y,z) 형식으로 일일히 쓰지 않아도 된다는 장점이 있습니다.

    마치며

    어떤 방식으로 하던 구현하는 건 차이가 없습니다. 하지만, 모듈화나 유지보수 측면에서 보면 figure, axes를 직접 제어하는 편이 더 좋습니다.

    함께보면 좋은글

    [Matplotlib] 애니메이션 만들기 초간단 방법

    ndarray 데이터로 그래프 그리기(matplotlib)

    matplotlib]여러개로 나누어서 그래프 출력(subplot)

    댓글

    Designed by JB FACTORY

    ....