반응형
In [1]:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
In [2]:
%matplotlib inline
In [3]:
# !sudo apt-get install -y fonts-nanum
# !sudo fc-cache -fv
# !rm ~/.cache/matplotlib -rf
In [5]:
# # Matplotlib 한글 폰트 오류 문제 해결
# from matplotlib import font_manager, rc
# font_path = '/content/drive/My Drive/Colab Notebooks/Fonts/NanumBarunGothic.ttf' # 폰트 파일 위치
# font_name = font_manager.FontProperties( fname = font_path ).get_name()
# rc( 'font', family = font_name )
# plt.rcParams['font.size'] = 15
In [3]:
plt.style.use(['seaborn-notebook'])
- plt.figure() : figure 객체 생성
- plt.axes : 눈금과 레이블이 있는 테두리박스 시각화 하는 플롯요소 포함...?
In [4]:
fig = plt.figure()
plt.plot([0,0.2,0.4,0.6,0.8,1] * 5); # 리스트가 들어감
In [5]:
x = np.arange(0,10, 0.01)
fig = plt.figure()
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
Out[5]:
In [6]:
fig = plt.figure(figsize=(5, 5))
plt.title("Plot")
plt.plot([1, 4, 9, 16])
plt.show()
In [7]:
plt.plot([10, 20, 30, 40], [1, 4, 9, 16], 'rs--')
plt.grid(True)
plt.show()
2. 선 여러개 그리기¶
In [8]:
t = np.arange(0.,5.,0.2)
plt.title("three lines")
plt.plot(t, t,'r--', t, t**2,'bs:', t, 0.2*t**3, 'c>-')
plt.grid(True)
plt.show()
3. x, y 범위 간격 정하기¶
: xlim(범위시작, 범위끝), : xticks(실제 x 값, 표시할 label)
In [9]:
fig = plt.figure(figsize= (5,7))
t = np.arange(0.,10.,0.2)
plt.title("three lines")
plt.plot(t, t,'r--', t, t**2,'bs:', t, 0.2*t**3, 'c>-')
plt.xlim(0,10)
plt.ylim(0,20)
plt.grid(True)
plt.show()
In [ ]:
### 표시 숫자 간격 1로 동일하게 맞추기
In [10]:
fig = plt.figure(figsize= (5,7))
t = np.arange(0.,10.,0.2)
plt.title("three lines")
plt.plot(t, t,'r--', t, t**2,'bs:', t, 0.2*t**3, 'c>-')
plt.xticks([i for i in range(10)])
plt.yticks([i for i in range(20)])
plt.ylim(0,20)
plt.grid(True)
plt.show()
4. 범례¶
: plt.legend(loc = 2) 으로 표현 : 각 플롯에 label 있어야만 범례생성됨.
In [11]:
fig = plt.figure(figsize= (5,7))
t = np.arange(0.,10.,0.2)
plt.title("three lines")
plt.plot(t, t,'r--',label = "2019")
plt.plot(t, 0.2*t**3, 'c>-', label = "2020")
plt.xticks([i for i in range(10)])
plt.yticks([i for i in range(20)])
plt.legend(loc = 4)
plt.ylim(0,20)
plt.grid(True)
plt.show()
Q.¶
여러가지 함수를 사용하여 아래 조건에 맞는 그래프를 그린다.
xlabel, ylabel, title을 모두 갖추고 있어야 한다.
하나의 Figure(일단, 그림이라고 이해한다. 아래에 자세한 설명이 있다.)에 3개 이상의 Plot을 그린다.
각 Plot은 다른 선, 마크, 색 스타일을 가진다.
legend는 그래프와 겹치지 않는 곳에 위치 시키도록 한다.
In [13]:
t = np.random.randint(500,1000, size = (12,))
t2 = np.random.randint(500,1000, size = (12,))
idx = np.arange(1,13)
idx
Out[13]:
In [17]:
fig = plt.figure(figsize = (10,5))
plt.title("sales - 3 years")
plt.plot(idx, t, 'rs--', label = '2019')
plt.plot(idx, t2, 'c>-', label = '2020')
plt.xticks(idx, ['jan','feb','mar','apr','may','june','jul','aug','sep','oct','nov','dec'])
plt.ylim(500,1000)
plt.legend(loc = 2)
plt.grid(True)
plt.show()
Figure 객ㅊㅔ 대체 뭐임¶
: plot 명령 등을 실행하면 자동으로 Figure를 생성해주기 때문에 일반적으로는 figure 명령을 잘 사용하지 않는다.
figure 명령을 명시적으로 사용하는 경우는 여러개의 윈도우를 동시에 띄워야 하거나(line plot이 아닌 경우), Jupyter 노트북 등에서(line plot의 경우) 그림의 크기를 설정하고 싶을 때이다.
그림의 크기는 figsize 인수로 설정한다.
In [19]:
f1 = plt.figure(1)
# plt.title("현재의 Figure 객체")
plt.plot([1, 2, 3, 4], 'ro:')
f2 = plt.gcf() ## 변수에 할당
print(f1, id(f1))
print(f2, id(f2))
plt.show()
표 2개 그리기 - Axes 객체와 subplots¶
: Figure가 행렬(matrix)이고 Axes가 행렬의 원소라고 생각하면 된다.
: plt.subplots(m,n,k)
: 전체 m*n 매트릭스의 K번째 도표
In [20]:
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
In [51]:
## 방법 2 : 2개 subplot 으로 그리기
fig, ax = plt.subplots(2,1) ### 객체 생성할때는 subplots!!!!!
ax[0].plot(x1,y1,'yo-')
plt.title('First plot')
plt.grid(True)
ax[1].plot(x2,y2,'ro-')
plt.title('First plot')
plt.grid(True)
plt.show()
In [27]:
## 방법 2 : 2개 subplot 으로 그리기
fig = plt.figure(figsize = (10,10))
ax1 = plt.subplot(2,1,1)
plt.plot(x1,y1,'yo-')
plt.title('First plot')
plt.grid(True)
ax2= plt.subplot(2,1,2)
plt.plot(x2,y2,'r.-')
plt.title('Second plot')
plt.grid(True)
plt.show()
In [30]:
np.random.rand(5)
Out[30]:
In [32]:
## 4개 2*2 로 만들기 -- 각각의 이름도 붙이기 matrix1
fig = plt.figure(figsize = (10,10))
plt.subplot(221)
plt.plot(np.random.rand(5))
plt.grid(True)
plt.title('matrix1')
plt.subplot(222)
plt.plot(np.random.rand(5))
plt.grid(True)
plt.title('matrix2')
plt.subplot(223)
plt.plot(np.random.rand(5))
plt.grid(True)
plt.title('matrix3')
plt.subplot(224)
plt.plot(np.random.rand(5))
plt.grid(True)
plt.title('matrix4')
Out[32]:
In [43]:
### 미리 와꾸 생성 후 할당도 가능함 --> 이 방법을 손에 익히자 이게 더 쉬운거 같음 !!
fig, ax = plt.subplots(2, 2)
ax[0,0].plot(np.random.rand(5))
ax[0,1].plot(np.random.rand(5))
ax[1,0].plot(np.random.rand(5))
ax[1,1].plot(np.random.rand(5))
plt.tight_layout()
plt.show()
축 두개로 표현하기 - Axis 객체와 축¶
: subplot() 이랑 twinx() 쓰면 됨 !!!!
In [56]:
fig, ax0 = plt.subplots()
ax1 = ax0.twinx()
ax0.plot([10, 5, 2, 9, 7], 'r-',label = "y0")
ax1.plot([100,200,220,180,120],'g:',label = 'y1')
plt.show()
In [ ]:
In [ ]:
In [ ]:
728x90
반응형
댓글