ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [파이썬] matplotlib으로 다중 꺾은선 그래프 그리기
    파이썬 배우기 2023. 11. 21. 15:31

    파이썬으로 그래프를 그릴 때마다 항상 검색을 해서 원하는 모양으로 바꾸고, 추가하고, 수정을 하는 것 같습니다. 그도 그럴 것이 pyplot 안에 많은 내장함수와 그 함수에 대한 다양한 파라미터들이 존재하는데요, 지금 버전만 해도 257개의 내장함수가 존재합니다. 

    import matplotlib.pyplot as plt
    from matplotlib import font_manager, rc 
    import pandas as pd
    
    len(dir(plt)) # 257

     

    그래서 오늘은 기본이되는 꺾은선 그래프를 그려보고, 변형을 원할 때 참고할 사이트를 알려드리겠습니다. 

    1. Multiple line graph : 하나의 도화지에 두 개의 꺾은선그래프 그리기

    2. subplot : 도화지를 두 개 만들어서 꺾은선 그래프 각각 넣기

     

    1. Multiple line graph 

    import random
    
    # sample 은 2010에서 2023까지 중복 없이 14개의 숫자를 가지는 랜덤 리스트를 만들 것이다
    t = sorted(random.sample(range(2010,2024),14))
    # sample 은 0에서 40까지 중복 없이 14개의 숫자를 가지는 랜덤 리스트를 만들 것이다
    y1 = random.sample(range(0,40),14)
    # sample 은 20에서 60까지 중복 허용하여 14개의 숫자를 가지는 랜덤 리스트를 만들 것이다
    y2 = random.choices(range(20,60),k=14)
    
    plt.plot(t,y1, 'red', linewidth=2, label='y1')
    plt.plot(t,y2, color='blue', marker='o', linestyle='dashed', linewidth=2, markersize=5, label='y2')
    
    plt.grid()
    plt.xlim([2010, 2023])
    plt.xticks(t, rotation = 45)
    plt.xlabel('년도')
    plt.ylabel('y축')
    plt.title('제목')
    plt.legend(loc='best', ncol=2, fontsize=10, frameon=True, shadow=True)
    
    plt.show()

     

    2. subplot

    import random
    
    # sample 은 2010에서 2023까지 중복 없이 14개의 숫자를 가지는 랜덤 리스트를 만들 것이다
    t = sorted(random.sample(range(2010,2024),14))
    # sample 은 0에서 40까지 중복 없이 14개의 숫자를 가지는 랜덤 리스트를 만들 것이다
    y1 = random.sample(range(0,40),14)
    # sample 은 20에서 60까지 중복 허용하여 14개의 숫자를 가지는 랜덤 리스트를 만들 것이다
    y2 = random.choices(range(20,60),k=14)
    
    plt.subplot(2, 1, 1)
    
    plt.plot(t, y1, "red", linewidth=2, label='y1')
    plt.grid()
    plt.xlim([2010, 2023])
    plt.xticks(t, rotation = 45)
    plt.xlabel("년도")
    plt.ylabel('y축')
    plt.title('년도별 y1 변화량')
    plt.legend(loc='best', ncol=2, fontsize=10, frameon=True, shadow=True)
    
    
    plt.subplot(2, 1, 2)
    
    plt.plot(t, y2, "blue", marker='o', linestyle='dashed', linewidth=2, markersize=5, label='y2')
    plt.grid()
    plt.xlim([2010, 2023])
    plt.xticks(t, rotation = 45)
    plt.xlabel("년도")
    plt.ylabel('y축')
    plt.title('년도별 y2 변화량')
    plt.legend(loc='best', ncol=2, fontsize=10, frameon=True, shadow=True)
    
    plt.tight_layout()
    plt.show()

     

    더 다양한 기능을 활용하고 싶으시면 

    https://github.com/matplotlib/cheatsheets 에서 더 많은 기능을 찾아보시는 것을 추천드립니다.

    그러면 아래와 같은 handouts 다운받을 수 있는데 가지고 다니면서 어떤 기능이 있고 어떻게 사용하는지 확인하실 수 있습니다!

Designed by Tistory.