Line Plot¶
In [1]:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
In [2]:
fig, axes = plt.subplots(1, 2, figsize=(12, 7))
x1 = [1, 2, 3, 4, 5]
x2 = [1, 3, 2, 4, 5]
y = [1, 3, 2, 1, 5]
axes[0].plot(x1, y)
axes[1].plot(x2, y)
plt.show()
In [3]:
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111, aspect=1)
n = 1000
x = np.sin(np.linspace(0, 2*np.pi, n))
y = np.cos(np.linspace(0, 2*np.pi, n))
ax.plot(x, y)
plt.show()
In [12]:
fig, axes = plt.subplots(1, 5, figsize=(12, 5))
np.random.seed(97)
x = np.arange(7)
y = np.random.rand(7)
i = 0
for line in ['solid','dashed','dashdot','dotted','None']:
axes[i].plot(x, y,
color='black',
marker='*',
linestyle=line)
i+=1
plt.show()
실전 데이터 시각화 ( 미국 주식 데이터셋 )¶
In [14]:
stock = pd.read_csv('./prices.csv')
stock
stock['date'] = pd.to_datetime(stock['date'], format='%Y-%m-%d', errors='raise')
stock.set_index("date", inplace = True)
stock.head(3)
Out[14]:
symbol | open | close | low | high | volume | |
---|---|---|---|---|---|---|
date | ||||||
2016-01-05 | WLTW | 123.430000 | 125.839996 | 122.309998 | 126.250000 | 2163600.0 |
2016-01-06 | WLTW | 125.239998 | 119.980003 | 119.940002 | 125.540001 | 2386400.0 |
2016-01-07 | WLTW | 116.379997 | 114.949997 | 114.930000 | 119.739998 | 2489500.0 |
In [20]:
stock['symbol'].unique()
Out[20]:
array(['WLTW', 'A', 'AAL', 'AAP', 'AAPL', 'ABC', 'ABT', 'ACN', 'ADBE',
'ADI', 'ADM', 'ADP', 'ADS', 'ADSK', 'AEE', 'AEP', 'AES', 'AET',
'AFL', 'AGN', 'AIG', 'AIZ', 'AJG', 'AKAM', 'ALB', 'ALK', 'ALL',
'ALXN', 'AMAT', 'AME', 'AMG', 'AMGN', 'AMP', 'AMT', 'AMZN', 'AN',
'ANTM', 'AON', 'APA', 'APC', 'APD', 'APH', 'ARNC', 'ATVI', 'AVB',
'AVGO', 'AVY', 'AWK', 'AXP', 'AYI', 'AZO', 'BA', 'BAC', 'BAX',
'BBBY', 'BBT', 'BBY', 'BCR', 'BDX', 'BEN', 'BHI', 'BIIB', 'BK',
'BLK', 'BLL', 'BMY', 'BSX', 'BWA', 'BXP', 'C', 'CA', 'CAG', 'CAH',
'CAT', 'CB', 'CBG', 'CBS', 'CCI', 'CCL', 'CELG', 'CERN', 'CF',
'CHD', 'CHK', 'CHRW', 'CI', 'CINF', 'CL', 'CLX', 'CMA', 'CMCSA',
'CME', 'CMG', 'CMI', 'CMS', 'CNC', 'CNP', 'COF', 'COG', 'COH',
'COL', 'COO', 'COP', 'COST', 'CPB', 'CRM', 'CSCO', 'CSX', 'CTAS',
'CTL', 'CTSH', 'CTXS', 'CVS', 'CVX', 'CXO', 'D', 'DAL', 'DD', 'DE',
'DFS', 'DG', 'DGX', 'DHI', 'DHR', 'DIS', 'DISCA', 'DISCK', 'DLR',
'DLTR', 'DNB', 'DOV', 'DOW', 'DPS', 'DRI', 'DTE', 'DUK', 'DVA',
'DVN', 'EA', 'EBAY', 'ECL', 'ED', 'EFX', 'EIX', 'EL', 'EMN', 'EMR',
'ENDP', 'EOG', 'EQIX', 'EQR', 'EQT', 'ES', 'ESRX', 'ESS', 'ETFC',
'ETN', 'ETR', 'EW', 'EXC', 'EXPD', 'EXPE', 'EXR', 'F', 'FAST',
'FCX', 'FDX', 'FE', 'FFIV', 'FIS', 'FISV', 'FITB', 'FL', 'FLIR',
'FLR', 'FLS', 'FMC', 'FOX', 'FOXA', 'FRT', 'FSLR', 'FTI', 'FTR',
'GD', 'GE', 'GGP', 'GILD', 'GIS', 'GLW', 'GOOG', 'GOOGL', 'GPC',
'GPN', 'GPS', 'GRMN', 'GS', 'GT', 'GWW', 'HAL', 'HAR', 'HAS',
'HBAN', 'HBI', 'HCN', 'HCP', 'HD', 'HES', 'HIG', 'HOG', 'HOLX',
'HON', 'HP', 'HPQ', 'HRB', 'HRL', 'HRS', 'HSIC', 'HST', 'HSY',
'HUM', 'IBM', 'ICE', 'IDXX', 'IFF', 'ILMN', 'INTC', 'INTU', 'IP',
'IPG', 'IR', 'IRM', 'ISRG', 'ITW', 'IVZ', 'JBHT', 'JCI', 'JEC',
'JNJ', 'JNPR', 'JPM', 'JWN', 'K', 'KEY', 'KIM', 'KLAC', 'KMB',
'KMX', 'KO', 'KR', 'KSS', 'KSU', 'L', 'LB', 'LEG', 'LEN', 'LH',
'LKQ', 'LLL', 'LLTC', 'LLY', 'LMT', 'LNC', 'LNT', 'LOW', 'LRCX',
'LUK', 'LUV', 'LVLT', 'M', 'MA', 'MAA', 'MAC', 'MAR', 'MAS', 'MAT',
'MCD', 'MCHP', 'MCK', 'MCO', 'MDLZ', 'MDT', 'MET', 'MHK', 'MJN',
'MKC', 'MLM', 'MMC', 'MMM', 'MNST', 'MO', 'MON', 'MOS', 'MRK',
'MRO', 'MSFT', 'MSI', 'MTB', 'MTD', 'MU', 'MUR', 'MYL', 'NBL',
'NDAQ', 'NEE', 'NEM', 'NFLX', 'NFX', 'NI', 'NKE', 'NOC', 'NOV',
'NRG', 'NSC', 'NTAP', 'NTRS', 'NUE', 'NVDA', 'NWL', 'O', 'OKE',
'OMC', 'ORCL', 'ORLY', 'OXY', 'PAYX', 'PBCT', 'PBI', 'PCAR', 'PCG',
'PCLN', 'PDCO', 'PEG', 'PEP', 'PFE', 'PFG', 'PG', 'PGR', 'PH',
'PHM', 'PKI', 'PLD', 'PM', 'PNC', 'PNR', 'PNW', 'PPG', 'PPL',
'PRGO', 'PRU', 'PSA', 'PVH', 'PWR', 'PX', 'PXD', 'QCOM', 'R',
'RAI', 'RCL', 'REGN', 'RF', 'RHI', 'RHT', 'RIG', 'RL', 'ROK',
'ROP', 'ROST', 'RRC', 'RSG', 'RTN', 'SBUX', 'SCG', 'SCHW', 'SE',
'SEE', 'SHW', 'SIG', 'SJM', 'SLB', 'SLG', 'SNA', 'SNI', 'SO',
'SPG', 'SPGI', 'SPLS', 'SRCL', 'SRE', 'STI', 'STT', 'STX', 'STZ',
'SWK', 'SWKS', 'SWN', 'SYK', 'SYMC', 'SYY', 'T', 'TAP', 'TDC',
'TEL', 'TGNA', 'TGT', 'TIF', 'TJX', 'TMK', 'TMO', 'TROW', 'TRV',
'TSCO', 'TSN', 'TSO', 'TSS', 'TWX', 'TXN', 'TXT', 'UAA', 'UAL',
'UDR', 'UHS', 'ULTA', 'UNH', 'UNM', 'UNP', 'UPS', 'URBN', 'URI',
'USB', 'UTX', 'V', 'VAR', 'VFC', 'VIAB', 'VLO', 'VMC', 'VNO',
'VRSK', 'VRSN', 'VRTX', 'VTR', 'VZ', 'WAT', 'WBA', 'WDC', 'WEC',
'WFC', 'WFM', 'WHR', 'WM', 'WMB', 'WMT', 'WU', 'WY', 'WYN', 'WYNN',
'XEC', 'XEL', 'XL', 'XLNX', 'XOM', 'XRAY', 'XRX', 'YHOO', 'YUM',
'ZBH', 'ZION', 'AIV', 'CHTR', 'LYB', 'GM', 'ABBV', 'DLPH', 'FB',
'FBHS', 'HCA', 'KMI', 'KORS', 'MPC', 'NLSN', 'PSX', 'TDG', 'TRIP',
'XYL', 'ZTS', 'COTY', 'MNK', 'NWS', 'NWSA', 'EVHC', 'ALLE', 'CFG',
'NAVI', 'QRVO', 'SYF', 'WRK', 'KHC', 'PYPL', 'HPE', 'CSRA', 'FTV'],
dtype=object)
Apple과 Google 주식 종가 Line plot¶
In [22]:
apple = stock[stock['symbol'] == 'AAPL']
google = stock[stock['symbol'] == 'GOOGL']
In [23]:
fig, ax = plt.subplots(1, 1, figsize=(15, 7), dpi=300)
ax.plot(google.index, google['close'])
ax.plot(apple.index, apple['close'])
plt.show()
In [25]:
google.head(3)
Out[25]:
symbol | open | close | low | high | volume | |
---|---|---|---|---|---|---|
date | ||||||
2010-01-04 | GOOGL | 626.950006 | 626.750011 | 624.240011 | 629.510005 | 3908400.0 |
2010-01-05 | GOOGL | 627.180001 | 623.990017 | 621.540016 | 627.839984 | 6003300.0 |
2010-01-06 | GOOGL | 625.860033 | 608.260035 | 606.360021 | 625.860033 | 7949400.0 |
이동평균 df.rolling(window=20).mean()¶
In [26]:
google_rolling = google.rolling(window=20).mean()
In [39]:
from matplotlib.ticker import MultipleLocator
fig, axes = plt.subplots(2, 1, figsize=(12, 7), dpi=300, sharex=True)
axes[0].plot(google.index,google['close'])
axes[1].plot(google_rolling.index,google_rolling['close'])
plt.show()
MultipleLocator 사용하기¶
tick 줄 때 정수형태면 array 만들어 넣는 방법 말고 MultipleLocator 사용가능
from matplotlib.ticker import MultipleLocator
ax1.xaxis.set_major_locator(MultipleLocator(100)) # x축 tick 100씩 증가
ax1.yaxis.set_major_locator(MultipleLocator(20)) # y축
보간법 사용 -> 방대한 데이터 smooth 한 line plot¶
In [41]:
from scipy.interpolate import make_interp_spline, interp1d
import matplotlib.dates as dates
fig, ax = plt.subplots(1, 2, figsize=(20, 7), dpi=300)
date_np = google.index
value_np = google['close']
date_num = dates.date2num(date_np)
# smooth
date_num_smooth = np.linspace(date_num.min(), date_num.max(), 50)
spl = make_interp_spline(date_num, value_np, k=3)
value_np_smooth = spl(date_num_smooth)
# print
ax[0].plot(date_np, value_np)
ax[1].plot(dates.num2date(date_num_smooth), value_np_smooth)
plt.show()
이중 축 사용 twinx()¶
In [57]:
fig, ax1 = plt.subplots(figsize=(7,5), dpi=150)
# First Plot
color = 'royalblue'
ax1.plot(google.index, google['close'], color=color)
ax1.set_xlabel('date')
ax1.set_ylabel('close price', color=color)
ax1.tick_params(axis='y', labelcolor=color)
# # Second Plot
ax2 = ax1.twinx()
color = 'tomato'
ax2.plot(google.index, google['volume'], color=color)
ax2.set_ylabel('volume', color=color)
ax2.tick_params(axis='y', labelcolor=color)
ax1.set_title('Google Close Price & Volume', loc='left', fontsize=15)
plt.show()
이중 축 사용 secondary-xaxis() 과 text / min / max 포인트 주기¶
In [54]:
def deg2rad(x):
return x * np.pi / 180
def rad2deg(x):
return x * 180 / np.pi
fig = plt.figure(figsize=(12, 5))
x = np.linspace(0, 2*np.pi, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
# Ax2
ax = fig.add_subplot(111, aspect=1)
ax.plot(x, y1)
ax.plot(x, y2)
##################### 텍스트 주기
ax.text(x[-1]+0.1, y1[-1], s='sin', fontweight='bold',
va='center', ha='left',
bbox=dict(boxstyle='round,pad=0.3', fc='#1ABDE9', ec='black', alpha=0.3))
ax.text(x[-1]+0.1, y2[-1], s='cos', fontweight='bold',
va='center', ha='left',
bbox=dict(boxstyle='round,pad=0.3', fc='#F36E8E', ec='black', alpha=0.3))
##################### 이중 축 사용
secax = ax.secondary_xaxis('top', functions=(deg2rad, rad2deg))
secax.set_xlabel('angle [rad]')
##################### max 포인트와 line 플롯
ax.plot([-1, x[np.argmax(y1)]], [np.max(y1)]*2,
linestyle='--', color='tomato'
)
ax.scatter(x[np.argmax(y1)], np.max(y1),
c='tomato',s=50, zorder=20)
##################### min 포인트와 line 플롯
ax.plot([-1, x[np.argmin(y1)]], [np.min(y1)]*2,
linestyle='--', color='royalblue'
)
ax.scatter(x[np.argmin(y1)], np.min(y1),
c='royalblue',s=50, zorder=20)
plt.show()
In [ ]:
'부스트캠프 AI Tech > Data Viz' 카테고리의 다른 글
[02] Bar Plot (0) | 2022.01.08 |
---|---|
[01] matplotlib (0) | 2022.01.07 |
[00] Markdown (0) | 2022.01.07 |