import numpy as np
import pandas as pd
PREVIOUS_MAX_ROWS = pd.options.display.max_rows
pd.options.display.max_rows = 20
np.random.seed(12345)
import matplotlib.pyplot as plt
import matplotlib
plt.rc('figure', figsize=(10, 6))
np.set_printoptions(precision=4, suppress=True)
# magic 명령어: 일반적인 작업이나 ipython 시스템 동작을 제어
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
data = np.arange(10)
data
plt.plot(data) #1~10의 data를 넣음.
# 새로운 figure 객체 생성
fig = plt.figure()
# fig 안에 2 x 2로 subplot 구성
# 그중 첫번째(좌상단, index=1) subplot 선택
ax1 = fig.add_subplot(2, 2, 1) #ax1 = 해당 subplot의 빈 좌표 평면(여기에 plot을 그림.)
ax2 = fig.add_subplot(2, 2, 2)
# 가장 최근의 figure와 subplot에 plot을 그림.
plt.plot([1.5, 3.5, -2, 1.6])
ax3 = fig.add_subplot(2, 2, 3)
plt.plot(np.random.randn(50).cumsum(), 'k--') #cumsum : 행, 열의 누적합 구함.
# hist: histogram(bar chart), bins: 구간수, color: 색상, alpha: 투명도
a = ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
print(a)
# scatter: 2차원 데이터 즉, 두 개의 실수 데이터 집합의 상관관계 표시
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))
plt.close('all')
fig, axes = plt.subplots(2, 3)
plt.tight_layout() #자동으로 레이아웃 설정
axes
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True) #축을 공유(범위, tick, 크기가 동일하게)
for i in range(2):
for j in range(2):
axes[i, j].hist(np.random.randn(500), bins=50, color='k', alpha=0.5)
plt.subplots_adjust(wspace=0, hspace=0)
plt.figure() #figure 생성
from numpy.random import randn
plt.plot(randn(30).cumsum(), 'rx--') #빨간색, x 마크, 점선'
plt.close('all')
data = np.random.randn(30).cumsum()
plt.plot(data, 'k--', label='Default')
plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post') #계단 형태의 그래프
plt.legend(loc='best') #best: 범례 위치
#일단 plot 하나 그리고
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())
plt.xlim() # x축 표시되는 범위 출력
# 눈금 위치 지정
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
# 눈금 이름/형태/폰트
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
rotation=30, fontsize='small')
# 그림 title
ax.set_title('My first matplotlib plot')
# X 축 이름
ax.set_xlabel('Stages')
from numpy.random import randn
fig = plt.figure();
ax = fig.add_subplot(1, 1, 1)
ax.plot(randn(1000).cumsum(), 'y', label='one')
ax.plot(randn(1000).cumsum(), 'r--', label='two')
ax.plot(randn(1000).cumsum(), 'b.', label='three')
ax.legend(loc='best')
from datetime import datetime
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
data = pd.read_csv('examples/spx.csv', index_col=0, parse_dates=True)
spx = data['SPX']
data spx
spx.plot(ax=ax, style='k-') #black, 실선
crisis_data = [
(datetime(2007, 10, 11), 'Peak of bull market'),
(datetime(2008, 3, 12), 'Bear Stearns Fails'),
(datetime(2008, 9, 15), 'Lehman Bankruptcy')
]
# 화살표와 주석 그리기
for date, label in crisis_data:
#주석내용, xy:좌표(xytext 있으면 의미 x), xytext:주석 좌표, arrowprops:화살표 특성,
#horizontalalignment:주석의 수평정렬, verticalalignment:수직정렬(top or bottom)
ax.annotate(label, xy=(date, spx.asof(date) + 75),
xytext=(date, spx.asof(date) + 225),
arrowprops=dict(facecolor='black', headwidth=4, width=2,
headlength=4),
horizontalalignment='left', verticalalignment='top')
ax.set_xlim(['1/1/2007', '1/1/2011'])
ax.set_ylim([600, 1800])
ax.set_title('Important dates in the 2008-2009 financial crisis')
fig = plt.figure(figsize=(12, 6));
ax = fig.add_subplot(1, 1, 1)
rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3) #(x,y) 좌표, x 폭, y 높이
circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3) # 원 중심 (x, y), 반지름
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]], # 다형의 각 점
color='g', alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
plt.savefig('figpath.png', dpi=400, bbox_inches='tight')
plt.close('all')
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
print(s)
s.plot()
df = pd.DataFrame(np.random.randn(10, 4).cumsum(0),
columns=['A', 'B', 'C', 'D'],
index=np.arange(0, 100, 10))
df.plot()
fig, axes = plt.subplots(2, 1)
data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))
data.plot(kind='bar', ax=axes[0], color='k', alpha=0.7, rot=0) #alpha:투명도
# data.plot.bar(ax=axes[0], color='k', alpha=0.7, rot=0)
data.plot.barh(ax=axes[1], color='k', alpha=0.7)
# data.plot(kind='barh' ax=axes[1], color='k', alpha=0.7)
np.random.seed(12348)\
df = pd.DataFrame(np.random.rand(6, 4),
index=['one', 'two', 'three', 'four', 'five', 'six'],
columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))
print(df)
Genus A B C D
one 0.370670 0.602792 0.229159 0.486744
two 0.420082 0.571653 0.049024 0.880592
three 0.814568 0.277160 0.880316 0.431326
four 0.374020 0.899420 0.460304 0.100843
five 0.433270 0.125107 0.494675 0.961825
six 0.601648 0.478576 0.205690 0.560547
df.plot.bar()
df.plot.barh(stacked=True, alpha=0.5)
plt.close('all')
tips = pd.read_csv('examples/tips.csv')
tips
party_counts = pd.crosstab(tips['day'], tips['size']) #day가 index, size가 열(col)
party_counts
party_counts = party_counts.loc[:, 2:5] #인덱스는 수 그대로
party_counts
# 각 row의 합이 1이 되게 Normalize
party_pcts = party_counts.div(party_counts.sum(1), axis=0)
party_pcts
party_pcts.plot.bar(rot=0) # 글씨 회전 (ex) 45, 90,,,)
plt.close('all')
import seaborn as sns
tips = sns.load_dataset("tips")
# tip을 제외한 party 비용 대비 tip 비율
tips['tip_pct'] = tips['tip'] / (tips['total_bill'] - tips['tip'])
tips.head()
sns.barplot(x='tip_pct', y='day', data=tips, orient='h')
#sns.barplot(y='tip_pct', x='day', data=tips, orient='v')
plt.close('all')
sns.barplot(x='tip_pct', y='day', hue='time', data=tips, orient='h')
plt.figure()
import seaborn as sns
tips = sns.load_dataset("tips")
tips['tip_pct'].plot.hist(bins=50)
plt.figure()
tips['tip_pct'].plot.density()
# tips['tip_pct'].plot(kind='kde') 도 동일
import numpy as np
plt.figure()
#두 개의 정규분포 자료
comp1 = np.random.normal(0, 1, size=200) # N(0,1): 평균 0, 표준편차 1
comp2 = np.random.normal(10, 2, size=200) # N(10,2)
values = pd.Series(np.concatenate([comp1, comp2])) #배열들을 하나로 합침.
values
0 0.203887
1 -2.213737
2 0.315042
3 -0.137200
4 0.036238
...
395 10.636197
396 9.259458
397 10.182617
398 10.686063
399 10.864287
sns.distplot(values, bins=100, color='k')
macro = pd.read_csv('examples/macrodata.csv')
data = macro[['cpi', 'm1', 'tbilrate', 'unemp']] #열(col)을 지정
trans_data = np.log(data).diff().dropna() #로그 차이를 계산
trans_data[: 5] #5개 행만 출력
plt.figure()
sns.regplot('m1', 'unemp', data=trans_data) #x축은 'm1' 열, y축은 'unemp' 열
plt.title('Changes in log %s versus log %s' % ('m1', 'unemp'))
sns.pairplot(trans_data, diag_kind='kde', plot_kws={'alpha': 0.2})
from pandas.plotting import scatter_matrix
plt.figure()
scatter_matrix(trans_data,
alpha=1, ## 데이터 포인트의 투명도 1 = 가장진함, 0 = 완전투명
figsize=(10,10), ## 캔버스 사이즈 조절
diagonal=None) ## 대각 원소에는 아무것도 그리지 않는다.
plt.show()
plt.figure()
plt.scatter(trans_data['m1'], trans_data['unemp'])
plt.title('Changes in log %s vs. log %s' % ('m1', 'unemp'))
from pandas.plotting import scatter_matrix
pd.plotting.scatter_matrix(trans_data, diagonal='kde', color='k', alpha=0.3)
plt.show()
sns.factorplot(x='day', y='tip_pct', hue='time', col='smoker',
kind='bar', data=tips[tips.tip_pct < 1])
sns.factorplot(x='day', y='tip_pct', row='time',
col='smoker',
kind='bar', data=tips[tips.tip_pct < 1])
sns.factorplot(x='tip_pct', y='day', kind='box',
data=tips[tips.tip_pct < 0.5])