04wk-1

matplotlib
Author

최규빈

Published

September 26, 2022

산점도 응용예제 4 (무상관과 독립), mpl의 미세먼지 팁 (1)

강의영상

https://youtube.com/playlist?list=PLQqh36zP38-zZsodh1GEp1w8cDYu_GFrl

imports

import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd

산점도 응용예제 4 (무상관과 독립)

예제자료

예시1: 사각형

x1 = np.random.uniform(low=-1,high=1,size=10000)
y1 = np.random.uniform(low=-1,high=1,size=10000)
plt.plot(x1,y1,',')

예시2: 원

_r2 = x1**2+y1**2
x2=x1[_r2<1]
y2=y1[_r2<1]
plt.plot(x2,y2,',')

예시3: 이변량정규분포

x3 = np.random.randn(10000)
y3 = np.random.randn(10000)
plt.plot(x3,y3,',')

상관계수

- 예시1, 예시2, 예시3의 산점도를 보고 상관계수가 얼마인지 예상해보라. 실제 계산결과와 확인하라.

np.corrcoef([x1,y1])
array([[ 1.        , -0.00255095],
       [-0.00255095,  1.        ]])
np.corrcoef([x2,y2])
array([[ 1.        , -0.01437794],
       [-0.01437794,  1.        ]])
np.corrcoef([x3,y3])
array([[ 1.        , -0.02282708],
       [-0.02282708,  1.        ]])

독립

- 예시1,2,3 중 독립인것은 무엇인가?

- 예시1 vs 예시2

fig, ax = plt.subplots(1,2,figsize=(8,4)) 
ax[0].plot(x1,y1,',',color='gray')
ax[1].plot(x2,y2,',',color='gray')

def g(intval, data, ax, col = 'r'):
    a,b = intval
    x,y = data
    idx = (a<x)&(x<b) 
    ax.plot(x[idx],y[idx],',',color=col)
g([-0.1,0.1],[x1,y1],ax[0])
g([-0.1,0.1],[x2,y2],ax[1])
fig

g([0.79,0.99],[x1,y1],ax[0],col='b')
g([0.79,0.99],[x2,y2],ax[1],col='b')
fig

- 예시3

fig,ax = plt.subplots()
ax.plot(x3,y3,',',color='gray')

g([-2.5,-1.5],[x3,y3],ax,col='r')
g([-0.5,+0.5],[x3,y3],ax,col='b')
g([+1.5,+2.5],[x3,y3],ax,col='g')
fig

def h(intval, data, ax, col):
    a,b = intval
    x,y = data 
    idx = (a<x) & (x<b) 
    ax.hist(y[idx],color=col) 
fig,ax = plt.subplots(5,2,figsize=(8,16))
ax[0,0].plot(x3,y3,',',color='gray'); g([-2.5,-1.5],[x3,y3],ax[0,0],col='r')
ax[1,0].plot(x3,y3,',',color='gray'); g([-1.5,-0.5],[x3,y3],ax[1,0],col='g')
ax[2,0].plot(x3,y3,',',color='gray'); g([-0.5,+0.5],[x3,y3],ax[2,0],col='b')
ax[3,0].plot(x3,y3,',',color='gray'); g([+0.5,+1.5],[x3,y3],ax[3,0],col='m')
ax[4,0].plot(x3,y3,',',color='gray'); g([+1.5,+2.5],[x3,y3],ax[4,0],col='lime')

h([-2.5,-1.5],[x3,y3],ax[0,1],col='r')
h([-1.5,-0.5],[x3,y3],ax[1,1],col='g')
h([-0.5,+0.5],[x3,y3],ax[2,1],col='b')
h([+0.5,+1.5],[x3,y3],ax[3,1],col='m')
h([+1.5,+2.5],[x3,y3],ax[4,1],col='lime')

mpl에 대한 미세먼지 팁 (1)

그림만 보고 싶을때

plt.plot([1,2,3,4],[2,3,4,5]);

marker size, line width

plt.plot([1,2,3,4],[2,3,4,2],'o',ms=10)

plt.plot([1,2,3,4],[2,3,4,5],'--',lw=10)

label + legend

plt.plot([1,2,3,4],[1,2,3,2],'--o',label='A')
plt.plot([1,2,3,4],[3,2.1,1,3],'--o',label='B')
plt.legend()
<matplotlib.legend.Legend at 0x7f5889ead210>

색깔조정 (C0,C1,…)

plt.plot([1,2,3,4],[1,2,3,2],'--o',label='A',color='C1')
plt.plot([1,2,3,4],[3,2.1,1,3],'--o',label='B',color='C0')
plt.legend()
<matplotlib.legend.Legend at 0x7f588a29ef10>

title 설정

- (방법1)

plt.plot([1,2,3,4],[1,2,3,2],'--o',label='A',color='C1')
plt.plot([1,2,3,4],[3,2.1,1,3],'--o',label='B',color='C0')
plt.legend()
plt.title('title')
Text(0.5, 1.0, 'title')

- (방법2)

fig, ax = plt.subplots()
ax.plot([1,2,3,4],[1,2,3,2],'--o',label='A',color='C1')
ax.plot([1,2,3,4],[3,2.1,1,3],'--o',label='B',color='C0')
ax.legend()
ax.set_title('title')
Text(0.5, 1.0, 'title')

suptitle 설정

fig, ax = plt.subplots(2,2)
ax[0,0].plot([1,2,3,2],'--o',label='A',color='C0')
ax[0,0].set_title('(a)')
ax[0,1].plot([3,2.1,1,3],'--o',label='B',color='C1')
ax[0,1].set_title('(b)')
ax[1,0].plot([-3,-2.1,-1,-3],'--o',label='B',color='C2')
ax[1,0].set_title('(c)')
ax[1,1].plot([3,-2.1,1,-3],'--o',label='B',color='C3')
ax[1,1].set_title('(d)')
#plt.suptitle('suptitle')
fig.suptitle('suptitle')
Text(0.5, 0.98, 'suptitle')

tight_layout()

fig

fig.tight_layout()
fig

fig, ax, plt 소속

- 일단 그림 하나 그리고 이야기좀 해보자.

fig, ax = plt.subplots()
ax.plot([1,2,3,1])

- fig에는 있고 ax에는 없는 것

add_axes, tight_layout, suptitle, …

- ax에는 있고 fig에는 없는 것

boxplot, hist, plot, set_title, …

- plt는 대부분 다 있음. (의미상 명확한건 대충 알아서 fig, ax에 접근해서 처리해준다)

  • plt.tight_layout, plt.suptitle, plt.boxplot, plt.hist, plot.plot
  • plt.set_title 은 없지만 plt.title 은 있음
  • plt.add_axes 는 없음..

x축, y축 label 설정

ax.xaxis.set_label_text('xlabel',size=16,family='serif',weight=1000,style='italic')
#_fontsettings={'size':16,'family':'serif','weight'=1000,'style':'italic'}
#ax.xaxis.set_label_text('xlabel',_fontsettings)
fig

폰트ref - size: - fontweight: 0~1000 - family: ‘serif’, ‘sans-serif’, ‘monospace’ - style: ‘normal’, ‘italic’

ax.set_ylabel('ylabel',size=16)
fig

숙제 (난이도 상) – 다음시간에 풀어줄거에요

아래와 같이 표준정규분포에서 100개의 난수를 생성하여 \(\boldsymbol{\epsilon}=(\epsilon_1,\epsilon_2,\dots,\epsilon_{100})\) 와 같은 벡터를 만들었다고 하자.

np.random.seed(43052)
ϵ = np.random.randn(100)

아래는 \((t,\epsilon_t)\)를 그린 그림이다. (단 \(t=1,2,\dots,100\))

plt.plot(np.arange(1,101),ϵ,'--o') 

(1) \(\epsilon_t\)\(\epsilon_{t-1}\)은 독립이라고 보여지는가?

(2) 아래의 수식을 만족하는 벡터 \({\boldsymbol y} = (y_1,y_2,\dots, y_{100})\) 을 생성하라. (단 \(y_1=\epsilon_1\))

\[ y_t = y_{t-1} + \epsilon_t\]

(3) \((t,y_t)\)의 dot-connected plot을 그려라.

# 아래와 같은 그림이 나와야 한다. 

(4) \(y_t\)\(y_{t-1}\)은 독립이라고 볼 수 있는가?