Python/Visualization
Matplotlib _ basic (OOP Method & Multi Plot & Font & Minus)
MINSU KANG
2021. 1. 27. 20:53
Matplotlib의 대한 기본적인 방식이다. 사용하는데 있어 시작하는 포맷이고, 아마 여기서 추가로 업데이트를 하면 될 것 같다. 추가로 판다스를 이용해서도 심플하게 그리는 방법도 첨부했다
그리고 폰트 관련 이슈와 마이너스 부호도 첨부했다
import numpy as np
import pandas as pd
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
pd.set_option('display.float_format', lambda x: '%.3f' % x)
pd.set_option('max_columns', None)
#%% example1
import matplotlib.pyplot as plt
import FinanceDataReader as fdr
# 한글폰트 및 마이너스 부호 살리는 법
import matplotlib as mpl
import matplotlib.font_manager as fm
for f in fm.fontManager.ttflist:
if 'Gothic' in f.name:
print((f.name, f.fname))
plt.rcParams["font.family"] = 'Yu Gothic'
mpl.rcParams['axes.unicode_minus'] = False
samsung_df = fdr.DataReader('005390', '2017-01-01', '2017-12-31')
samsung_df.head()
# Stateless(or object-oriented) 방식
'''
- Matplotlib의 각 component를 하나의 object로 받아서, 함수 실행 및 property 설정/변경
- figure, ax(es)를 먼저 생성한다음, 하나하나 더하고, 적용하는 식
- 적용과정이 명시적으로 코드로 드러나기 때문에 조금 더 직관적임
'''
#1. Simple Example
x = [-3, 5, 7]
y = [10, 2, 5]
fig, ax = plt.subplots(figsize = (15,3)) # 클래스 생성
type(fig)
type(ax)
ax.plot(x, y)
ax.set_xlim(0, 10)
ax.set_ylim(-3, 8)
ax.set_xlabel('X axis')
ax.set_ylabel("Y axis")
ax.set_title("Line Plot")
fig.suptitle("Figure Title", size = 10, y = 1.03)
#%% example2
#2. 2x1 Subplots
SKC = fdr.DataReader("011790", start = "2019-01-01", end="2021-01-25") #SKC
TYHoldings = fdr.DataReader("363280") #티와이홀딩스
close_series1 = SKC['Close']
close_series2 = TYHoldings['Close']
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(14,10), sharex = True)
ax1 = axes[0]
ax2 = axes[1]
# ax1
ax1.plot(close_series1.index, close_series1, linewidth=2, linestyle="--", label="SKC")
_ = ax1.set_title("SKC Price", fontsize=15, family="Arial")
_ = ax1.set_ylabel("SKC Price", fontsize=15, family="Arial")
_ = ax1.set_xlabel("date", fontsize=15, family="Arial")
ax1.legend(loc = "upper left")
ax2.plot(close_series2.index, close_series2, linewidth = 2, linestyle = "--", label = "TYHolidngs")
_ = ax2.set_title("TYHolidngs Price", fontsize = 15, family="Arial")
_ = ax2.set_ylabel("TYHolidngs Price", fontsize = 15, family="Arial")
_ = ax2.set_xlabel("date", fontsize = 15, family="Arial")
ax2.legend(loc="upper left")
fig.suptitle("SKC & TYHoldings Price", family="Arial")
#%% Example3
#3. Pandas Plot Using groupby
skcPrice = fdr.DataReader("011790", start = "2019-01-01", end = "2021-01-25")['Close']
tyHoldingsPrice = fdr.DataReader("363280", start = "2019-01-01", end = "2021-01-25")['Close']
nobatexPrice = fdr.DataReader("285490", start = "2019-01-01", end = "2021-01-25")['Close']
df = pd.concat([skcPrice, tyHoldingsPrice, nobatexPrice], axis = 1)
df.columns = ['SKC Prcie', 'TYHoldings', 'Nobatex']
df_max = df.groupby([df.index.year,df.index.month]).max()
df_max.plot()
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(16,4))
df_max.plot(ax=ax1, kind = 'line')
df_max.plot(ax=ax2, kind = 'bar')
df_max.plot(ax=ax3, kind = 'hist', bins = 30)
#%% example4
df = fdr.DataReader("011790", start = "2019-01-01", end = "2021-01-25")['Close']
fig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(16,4))
df.pct_change().plot(kind = 'kde', ax = ax1, title = 'kde')
df.pct_change().plot(kind = 'box', ax = ax2, title = 'box')
df.pct_change().plot(kind = 'hist', ax = ax3, title = 'hist', bins = 30)