상세 컨텐츠

본문 제목

파이썬 matplotlib 모듈 그래프에서 날짜 표시 바꾸기

파이썬

by 코딩트리01 2024. 1. 30. 16:48

본문

이전 블로그 참고

https://codingtree01.tistory.com/6

 

파이썬에서 LSTM 모델로 삼성전자 일주일 주가 예측하기

이번 포스팅은 파이썬과 머신러닝을 활용한 금융 데이터 분석과 실질적인 적용 사례를 보여준다. 모듈 불러오기 및 학습 날짜 범위 설정 import pandas as pd from pykrx import stock import tensorflow as tf from t

codingtree01.tistory.com

 

그래프를 보면 날짜가 왼쪽부터 0, 50, 100, 150, 200 ... 순서로 되어있는 것을 볼 수 있다.

이 날짜들의 순서를 거꾸로 뒤집기 보단(거꾸로 뒤집다가 데이터도 뒤집어 버릴 수 있다.), 날짜를 2024-01과 같은 형식으로 만드는 게 보기 편할 것 같다. 

 

날짜를 실제 OHLCV데이터의 날짜로 사용하기 위해서는 마지막 가시화 코드를 다음과 같이 바꾸면 된다.

# 예측 결과와 실제 데이터를 같이 시각화
plt.figure(figsize=(15, 6))
plt.plot(actual_prices, label='Actual Prices')
plt.plot(np.arange(len(actual_prices), len(actual_prices) + future_days), future_prices, label='Predicted Prices')
plt.title('Samsung Stock Price Prediction')
plt.xlabel('Days')
plt.ylabel('Price')
plt.legend()

# 마우스 호버 기능 활성화
cursor = mplcursors.cursor(hover=True)
cursor.connect("add", lambda sel: sel.annotation.set_text('Price: {}'.format(sel.target[1])))

plt.show()

(원래 코드)

# 실제 OHLCV 데이터의 날짜를 사용
actual_dates = combined_data.index
reversed_actual_dates = actual_dates[::-1]  # 날짜 순서 뒤집기

# 데이터 그리기 (날짜는 원래 순서로)
plt.figure(figsize=(15, 6))
plt.plot(actual_dates, actual_prices, label='Actual Prices')
# 미래 예측 날짜 배열 생성
future_dates = pd.date_range(start=actual_dates[-1] + pd.DateOffset(days=1), periods=future_days)
plt.plot(future_dates, future_prices, label='Predicted Prices')
plt.title('Samsung Stock Price Prediction')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.xticks(rotation=45)  # 날짜 라벨 회전

# 마우스 호버 기능 활성화
cursor = mplcursors.cursor(hover=True)
cursor.connect("add", lambda sel: sel.annotation.set_text('Price: {}'.format(sel.target[1])))

plt.show()

(수정된 코드)

관련글 더보기