IT일지/파이썬

[파이썬] matplotlib에서 주말 제외하고 plot 또는 bar 그래프 그리기

체험가 2024. 2. 18. 14:40
반응형

matplotlib로 주식 일봉 캔들 차트와 거래량을 나눠서 출력하려고 했는데 캔들 차트는 mplfinance.plot 입력값으로 데이터프레임에 주말값 빼고 넣으면 정상적으로 출력이 되었지만, 거래량을 matplotlib.pyplot으로 출력하려고 하니 x축값에 주말을 뺀 날짜를 넣어도 그래프에는 주말이 포함되어 출력되는 문제가 발생했습니다.

 

plt.bar에서 원하지 않는 주말 데이터가 포함되어 출력되는 상황을 간략화한 테스트 코드는 다음과 같습니다.

import matplotlib.pyplot as plt
from datetime import datetime
import random

date_strings = ['240110', '240111', '240112', '240115', '240116', '240117', '240118', '240119', '240122', '240123', '240124', '240125', '240126', '240129', '240130', '240131', '240201', '240202', '240205', '240206']
dates = [datetime.strptime(date, '%y%m%d') for date in date_strings]

value = [random.randint(1, 100) for _ in range(len(dates))]
 
plt.xlabel('Date')
plt.ylabel('Value')
plt.bar(dates, value)
plt.xticks(rotation=45)
plt.show()

 

date_strings를 문자열 그대로 사용하면

matplotlib.category> Using categorical units to plot a list of strings that are all parsable as floats or dates. If these strings should be plotted as numbers, cast to the appropriate data type before plotting.

이런 경고 메시지를 띄우는 경우가 있어서 dates 변수에 datetime값으로 변환해서 저장했습니다.

 

문제는 datetime으로 변경한 값으로 plot이나 bar 차트를 그리려고 하면

 

이런식으로 date_strings에는 없는 주말 날짜도 같이 출력되어서 주말 빼고 영업일에 해당하는 값만 쭈욱 연결되는 그래프를 얻을 수 없었습니다.


해결방법

 

plt.bar(x, y)에서 x에 datetime 등 날짜값이나 int, float 같은 숫자값을 넣으면 matplotlib에서 자동으로 입력값의 처음값부터 끝 값까지 자동으로 xticks에 집어넣어 사용자가 원하지 않는 데이터도 들어가는게 문제이므로 xticks를 직접 설정하는 방법으로 문제를 해결했습니다.

import matplotlib.pyplot as plt
from datetime import datetime
import random

date_strings = ['240110', '240111', '240112', '240115', '240116', '240117', '240118', '240119', '240122', '240123', '240124', '240125', '240126', '240129', '240130', '240131', '240201', '240202', '240205', '240206']

dates = [datetime.strptime(date, '%y%m%d') for date in date_strings]

value = [random.randint(1, 100) for _ in range(len(dates))]

plt.xlabel('Date')
plt.ylabel('Value')
plt.bar(range(len(dates)), value)
plt.xticks(range(len(dates)), date_strings, rotation=45)
plt.show()

 

문제상황 예시에서 아래처럼 변경하였습니다.

plt.bar(dates, value) -> plt.bar(range(len(dates)), value)
plt.xticks(rotation=45) -> plt.xticks(range(len(dates)), date_strings, rotation=45)

 

xticks는 그래프의 x축 눈금(label)을 지정하는데 사용되는 함수이며,

첫번째 입력값인 ticks는 x축에 표시할 눈금의 위치를 나타내는 리스트,

두번째 입력값인 lables는 ticks에서 지정한 위치에 표시될 눈금의 라벨(텍스트)입니다.

위와같이 변경한 다음 그래프를 출력하면 주말이 제외된 그래프를 출력할 수 있습니다.

728x90
반응형