import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns scatterplot
= [2,2]
mean = [[1,0.7],[0.7,1]]
cov =np.random.multivariate_normal(mean,cov,size=1000).T arr
=1000).T.shape np.random.multivariate_normal(mean,cov,size
(2, 1000)
len(arr) # len = 2 가 나온다는 것은 첫번째와 두번째 원소에 접근할 수 있다는 말
2
0].shape arr[
(1000,)
= arr x,y
'o') plt.plot(x,y,
-
matplotlib을 이용한 그림
= np.random.multivariate_normal([0,0],[[1,0],[0,1]],size=1000).T
x1,y1 = np.random.multivariate_normal([2,2],[[1,0.7],[0.7,1]],size=1000).T x2,y2
'o')
plt.plot(x1,y1,'o') plt.plot(x2,y2,
sns: aray
=None, x=x1, y=y1)
sns.scatterplot(data=None, x=x2, y=y2) sns.scatterplot(data
<AxesSubplot:>
sns: wide df
'x':x1,'y':y1}) pd.DataFrame({
x | y | |
---|---|---|
0 | 0.053500 | -1.258803 |
1 | -0.517300 | -0.273907 |
2 | -0.938688 | 0.582421 |
3 | 1.017930 | -0.223879 |
4 | 0.827941 | 0.519745 |
... | ... | ... |
995 | 1.317776 | -0.898103 |
996 | -0.054884 | 0.290131 |
997 | -0.082623 | 0.971652 |
998 | -0.796771 | -0.140001 |
999 | 0.030602 | 0.435023 |
1000 rows × 2 columns
=pd.DataFrame({'x':x1,'y':y1}),x='x',y='y')
sns.scatterplot(data=pd.DataFrame({'x':x2,'y':y2}),x='x',y='y')
sns.scatterplot(data# #sns.scatterplot(data=None,x=x2,y=y2)
<AxesSubplot:xlabel='x', ylabel='y'>
sns: long df
=np.concatenate([x1,x2])
x# np.array(list(x1) + list(x2))
# x1.tolist() + x2.tolist()
# 다 같은 코드이지만 cocaternate쓰는 방식이 제일 편하다
=np.concatenate([y1,y2])
y
=['x1']*len(x1) + ['x2']*len(x2) cat
=pd.DataFrame({'x':x, 'y':y, 'cat':cat})
df2 df2
x | y | cat | |
---|---|---|---|
0 | 0.082929 | 1.218634 | x1 |
1 | -0.019451 | -1.352701 | x1 |
2 | -1.253126 | 1.246169 | x1 |
3 | -0.343648 | 0.078081 | x1 |
4 | 0.479097 | -1.039999 | x1 |
... | ... | ... | ... |
1995 | 2.503038 | 2.350603 | x2 |
1996 | 1.940601 | 2.356207 | x2 |
1997 | 3.213965 | 2.769489 | x2 |
1998 | 1.203818 | -0.276493 | x2 |
1999 | 1.378763 | 1.914046 | x2 |
2000 rows × 3 columns
=df2, x='x', y='y', hue='cat') sns.scatterplot(data
<AxesSubplot:xlabel='x', ylabel='y'>
sns을 이용하여 matplotlib 액시즈에 그림 그리기 (\(\star\))
예제1
= plt.subplots()
fig, ax 1,2,4,3]) ax.plot([
ax
<AxesSubplot:>
= plt.subplots() fig, mypltax
=df2, x='x', y='y', hue='cat', ax=mypltax)
sns.scatterplot(data# ax라는 변수를 넣자
<AxesSubplot:xlabel='x', ylabel='y'>
# 오 sns에 ax넣으니 fig에 sns가 들어옴 fig
- seaborn에서 배우지 않은 내용을 matplotlib이용해서 사용가능함
= plt.subplots()
fig, mypltax =df2, x='x', y='y', hue='cat', ax=mypltax)
sns.scatterplot(data'coco babo')
mypltax.set_title('coco ddong') fig.suptitle(
Text(0.5, 0.98, 'coco ddong')
= plt.subplots(1,3, figsize=(12,4))
fig, ax 0].plot([1,2,4,3], '--o')
ax[=x1, y=y1, ax=ax[1])
sns.scatterplot(x=x1, y=y1, ax=ax[2]) # 겹쳐그리자
sns.scatterplot(x=x2, y=y2, ax=ax[-1]) # 겹쳐그리자
sns.scatterplot(x2].plot([1,2,4,3], '--m', lw=5) ax[
예제2
import cv2
!wget https://upload.wikimedia.org/wikipedia/commons/0/08/Unequalized_Hawkes_Bay_NZ.jpg
= cv2.imread('Unequalized_Hawkes_Bay_NZ.jpg',0) # 채널이 1개인 흑백이미지
img !rm Unequalized_Hawkes_Bay_NZ.jpg
--2023-02-25 16:17:39-- https://upload.wikimedia.org/wikipedia/commons/0/08/Unequalized_Hawkes_Bay_NZ.jpg
Resolving upload.wikimedia.org (upload.wikimedia.org)... 103.102.166.240, 2001:df2:e500:ed1a::2:b
Connecting to upload.wikimedia.org (upload.wikimedia.org)|103.102.166.240|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 110895 (108K) [image/jpeg]
Saving to: ‘Unequalized_Hawkes_Bay_NZ.jpg’
Unequalized_Hawkes_ 100%[===================>] 108.30K 553KB/s in 0.2s
2023-02-25 16:17:40 (553 KB/s) - ‘Unequalized_Hawkes_Bay_NZ.jpg’ saved [110895/110895]
=0,vmax=255,cmap='gray') plt.imshow(img,vmin
<matplotlib.image.AxesImage at 0x7f61e88d36d0>
= cv2.equalizeHist(img) img2
img.shape
(683, 1024)
683*1024,1) # 컬럼벡터
img.reshape(683*1024) #길이가 1 img.reshape(
array([127, 145, 149, ..., 146, 145, 144], dtype=uint8)
= plt.subplots(2,2, figsize=(10,5))
fig, ax 0,0].imshow(img,vmin=0,vmax=255,cmap='gray')
ax[#ax[0,1].hist(img.reshape(-1))
-1),ax=ax[0,1], bins=15, lw=0, kde=True, color='C1')
sns.histplot(img.reshape(1,0].imshow(img2,vmin=0,vmax=255,cmap='gray')
ax[-1),ax=ax[1,1], bins=15, lw=0, kde=True, color='C1') sns.histplot(img2.reshape(
<AxesSubplot:ylabel='Count'>
- ax[0,1]의 x축을 ax[1,1]의 x축과 맞춰서 비교해보고 싶다.
= plt.subplots(2,2, figsize=(10,5))
fig, ax 0,0].imshow(img,vmin=0,vmax=255,cmap='gray')
ax[-1),ax=ax[0,1], bins=15, lw=0, kde=True, color='C1')
sns.histplot(img.reshape(0,1].set_xlim(0,255)
ax[1,0].imshow(img2,vmin=0,vmax=255,cmap='gray')
ax[-1),ax=ax[1,1], bins=15, lw=0, kde=True, color='C1') sns.histplot(img2.reshape(
<AxesSubplot:ylabel='Count'>
mpl 미세먼지 팁(2)
축 간격조정
import matplotlib as mpl
= plt.subplots()
fig, ax /30)**2 for xi in range(30)],'--o')
ax.plot([(xi3)) # 큰 눈금간격을 3으로
ax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(1)) # 작은 눈금간격을 1로 ax.xaxis.set_minor_locator(mpl.ticker.MultipleLocator(
축 삭제
= plt.subplots()
fig, ax /30)**2 for xi in range(30)],'--o')
ax.plot([(xi# x축 눈금삭제
ax.xaxis.set_major_locator(mpl.ticker.NullLocator()) # y축 눈금삭제 ax.yaxis.set_major_locator(mpl.ticker.NullLocator())
축 범위조정
= plt.subplots()
fig, ax /30)**2 for xi in range(30)],'--o')
ax.plot([(xi-1,2)
ax.set_ylim(-5,35)
ax.set_xlim(#plt.ylim(-1,2) 위 ax와 같은 코드
#plt.xlim(-5,35)
(-5.0, 35.0)
gcf, gca
1,2,3,2])
plt.plot([=plt.gcf()
fig
# gcf: get current figure
'suptitle') fig.suptitle(
Text(0.5, 0.98, 'suptitle')
fig
= fig.gca()
ax
# gca: get current axes
'title')
ax.set_title( fig