import matplotlib.pyplot as plt
import numpy as np
- 라인 플랏과 산점도를 그리는 방법
- 여러 그림 그리기 (한 플랏에 그림을 겹치는 방법, subplot을 그리는 방법)
- fig, axes의 개념이해 (객체지향적 프로그래밍)
Line plot
기본플랏
-
예시
=[1,2,3,4]
x=[1,2,4,3] y
plt.plot(x,y)
모양변경
-
예시1
'--') #점선 plt.plot(x,y,
-
예시2
':') plt.plot(x,y,
-
예시3
'-.') plt.plot(x,y,
색상변경
-
예시1
'r') plt.plot(x,y,
-
예시2
'k') #블랙 plt.plot(x,y,
모양 + 색상변경
-
예시1
'--r') # r을 앞에 쓰든 뒤에 쓰든 나온다 plt.plot(x,y,
원리?
-
r--
등의 옵션은 Markers + Line Styles + Colors의 조합으로 표현 가능
ref : https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html
--r
: 점선(dashed)스타일 + 빨간색r--
: 빨간색 + 점선(dashed)스타일:k
: 점선(dotted)스타일 + 검은색k:
: 검은색 + 점선(dotted)스타일
-
우선 Marker를 무시하면 Line Styles + Color로 표현가능한 조합은 4*8 = 32개
(Line Styles) 모두 4개
character | description |
---|---|
‘-’ | solid line style |
‘–’ | dashed line style |
‘-.’ | dash-dot line style |
‘:’ | dotted line style |
(Color) 모두 8개
character | color |
---|---|
‘b’ | blue |
‘g’ | green |
‘r’ | red |
‘c’ | cyan |
‘m’ | magenta |
‘y’ | yellow |
‘k’ | black |
‘w’ | white |
-
예시1
'--m') plt.plot(x,y,
-
예시2
'-.c') plt.plot(x,y,
-
예시3: line style + color 조합으로 사용하든 color + line style 조합으로 사용하든 상관없음
'c-.') plt.plot(x,y,
-
예시4: line style을 중복으로 사용하거나 color를 중복으로 쓸 수 는 없다.
'--:') plt.plot(x,y,
ValueError: Illegal format string "--:"; two linestyle symbols
'rb') plt.plot(x,y,
ValueError: Illegal format string "rb"; two color symbols
-
예시5: 색이 사실 8개만 있는 것은 아니다.
ref: https://matplotlib.org/2.0.2/examples/color/named_colors.html
'--',color='aqua') # 8가지 색 외의 다른 것은 color= 옵션으로 줘야함 plt.plot(x,y,
-
예시6: 색을 바꾸려면 Hex코드를 밖아 넣는 방법이 젤 깔끔함
ref: https://htmlcolorcodes.com/
='#277E41') plt.plot(x,y,color
-
예시7: 라인스타일도 4개만 있지 않다
ref: https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html
='dashed') plt.plot(x,y,linestyle
=(0, (20, 5))) plt.plot(x,y,linestyle
=(0, (20, 1))) plt.plot(x,y,linestyle
Scatter plot
원리
-
그냥 마커를 설정하면 끝
ref: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html
character | description |
---|---|
‘.’ | point marker |
‘,’ | pixel marker |
‘o’ | circle marker |
‘v’ | triangle_down marker |
‘^’ | triangle_up marker |
‘<’ | triangle_left marker |
‘>’ | triangle_right marker |
‘1’ | tri_down marker |
‘2’ | tri_up marker |
‘3’ | tri_left marker |
‘4’ | tri_right marker |
‘8’ | octagon marker |
‘s’ | square marker |
‘p’ | pentagon marker |
‘P’ | plus (filled) marker |
’*’ | star marker |
‘h’ | hexagon1 marker |
‘H’ | hexagon2 marker |
‘+’ | plus marker |
‘x’ | x marker |
‘X’ | x (filled) marker |
‘D’ | diamond marker |
‘d’ | thin_diamond marker |
‘|’ | vline marker |
’_’ | hline marker |
'o') plt.plot(x,y,
기본플랏
'.') plt.plot(x,y,
'x') plt.plot(x,y,
색깔변경
'or') plt.plot(x,y,
'db') plt.plot(x,y,
'bx') plt.plot(x,y,
dot-connected plot
-
예시1: 마커와 라인스타일을 동시에 사용하면 dot-connected plot이 된다.
'o-') plt.plot(x,y,
-
예시2: 당연히 색도 적용가능
'o--r') plt.plot(x,y,
-
예시3: 서로 순서를 바꿔도 상관없다.
'r--o') plt.plot(x,y,
'ro--') plt.plot(x,y,
여러 그림 그리기
겹쳐그리기
-
예시1
= np.arange(-5,5,0.1)
x = np.random.randn(100)
ϵ = 2*x + ϵ y
'.b')
plt.plot(x,y,2*x,'r') plt.plot(x,
따로그리기(subplot) // 외우기
-
예시1
= plt.subplots(2)
fig, axs 0].plot(x,y,'.b')
axs[1].plot(x,2*x,'r') axs[
-
예시2
= plt.subplots(2,2)
fig, axs 0,0].plot(x,2*x,'--b')
axs[0,1].plot(x,ϵ,'.r')
axs[1,0].plot(x,y,'.r')
axs[1,1].plot(x,y,'.r')
axs[1,1].plot(x,2*x,'-b') axs[
fig와 axes의 이해: matplotlib으로 어렵게 그림을 기리는 방법
예제1
-
목표: plt.plot()을 이용하지 않고 아래의 그림을 그려보자.
1,2,3,4],[1,2,4,3],'or--') plt.plot([
-
구조: axis \(\subset\) axes \(\subset\) figure
ref: https://matplotlib.org/stable/gallery/showcase/anatomy.html#sphx-glr-gallery-showcase-anatomy-py
-
전략: Fig
을 만들고 (도화지를 준비) \(\to\) axes
를 만들고 (네모틀) \(\to\) axes
에 그림을 그린다.
-
그림객체를 생성한다.
= plt.figure() fig
<Figure size 432x288 with 0 Axes>
# 지금은 아무것도 없다 fig
<Figure size 432x288 with 0 Axes>
-
그림객체에는 여러 인스턴스+함수가 있는데 그중에서 axes도 있다. (그런데 그 와중에 plot method는 없다.)
# 비어있는 리스트 fig.axes
[]
-
axes추가
0,0,1,1]) # (0,0) 위치에 (1,1)인 액시즈(=네모틀)을 만들어라. fig.add_axes([
<Axes:>
fig.axes
[<Axes:>]
# 아까는 아무것도 없었는데 지금 도화지안에 네모틀이 들어가 있다. fig
-
첫번째 액시즈를 ax1으로 받음 (원래 axes1이어야하는데 그냥 편의상)
= fig.axes[0] ax1
id(fig.axes[0]), id(ax1)
(140307253185296, 140307253185296)
-
잠깐만! (fig오브젝트와 ax1 오브젝트는 포함관계에 있다.)
id(fig.axes[0]), id(ax1)
(140307253185296, 140307253185296)
-
또 잠깐만! (fig오브젝트에는 plot이 없지만 ax1에서는 plot가 있다.)
set(dir(fig)) & {'plot'}
set()
set(dir(ax1)) & {'plot'}
{'plot'}
-
ax1.plot()을 사용하여 그림을 그려보자.
1,2,3,4],[1,2,4,3],'--or') # 안되누? ax1.plot([
fig
예제2: 예제1의 응용
-
위에서 축을 하나 더 추가
fig.axes
[<Axes:>]
1,1,1,1,]) # (1,1) 위치에 (1,1)크기의 액자틀 추가 fig.add_axes([
<Axes:>
#추가해서 두개 fig.axes
[<Axes:>, <Axes:>]
fig
= fig.axes ax1, ax2
-
ax2에 파란선으로 그림을 그리자
1,2,3,4],[1,2,4,3],'--ob') ax2.plot([
fig
예제3: 응용(미니맵)
-
위의 상황에서 액시지를 하나 더 추가
0.65,0.1,0.3,0.3]) fig.add_axes([
<Axes:>
fig
-1].plot([1,2,3,4],[1,2,4,3],'xr') fig.axes[
fig
예제4: 재해석1
(ver1)
1,2,3,4],[1,2,4,3]) plt.plot([
(ver2)
ver1은 사실 아래가 연속적으로 실행된 축약구문임
= plt.figure()
fig
fig.add_axes([?,?,?,?])= fig.axes[0]
ax1 1,2,3,4],[1,2,4,3])
ax1.plot([ fig
예제5: 재해석2
= plt.subplots(2,2) fig, axs
= plt.subplots(2,2)
fig, axs 0,0].plot([1,2,3,4],[1,2,4,3],'.')
axs[0,1].plot([1,2,3,4],[1,2,4,3],'--r')
axs[1,0].plot([1,2,3,4],[1,2,4,3],'o--')
axs[1,1].plot([1,2,3,4],[1,2,4,3],'o--',color='lime') axs[
-
fig, axs = plt.subplots(2,2)
의 축약버전을 이해하면된다.
(ver1)
= plt.subplots(2,2) fig, axs
(ver2)
ver1은 사실 아래가 연속적으로 실행된 축약구문임
= plt.figure()
fig
fig.add_axes([?,?,?,?])
fig.add_axes([?,?,?,?])
fig.add_axes([?,?,?,?])
fig.add_axes([?,?,?,?])= fig.axes
ax1,ax2,ax3,ax4 = np.array(((ax1,ax2),(ax3,ax4))) axs
(ver3)
ver1은 아래와 같이 표현할 수도 있다.
= plt.figure()
fig = fig.subplots(2,2) axs
숙제
숙제1
= plt.subplots(2,3)
fig, axs 0,0].plot([1,2,3,4],[1,2,4,3],'or')
axs[0,1].plot([1,2,3,4],[1,2,4,3],'og')
axs[0,2].plot([1,2,3,4],[1,2,4,3],'ob')
axs[1,0].plot([1,2,3,4],[1,2,4,3],'or--')
axs[1,1].plot([1,2,3,4],[1,2,4,3],'og--')
axs[1,2].plot([1,2,3,4],[1,2,4,3],'ob--') axs[
숙제2
= [1,2,3,4], [1,2,1,1] x,y
= plt.figure() fig
<Figure size 432x288 with 0 Axes>
fig
<Figure size 432x288 with 0 Axes>
fig.axes
[]
0,0,1,1]) fig.add_axes([
<Axes:>
fig.axes
[<Axes:>]
fig
= fig.axes[0] ax1
'or') ax1.plot(x,y,
fig
0.5,0.5,1,1,]) fig.add_axes([
<Axes:>
fig
1,1,1,1,]) fig.add_axes([
<Axes:>
fig
= fig.axes ax1, ax2, ax3
'og')
ax2.plot(x,y,'ob') ax3.plot(x,y,
fig
숙제3
= np.arange(-5,5,0.1)
x = np.sin(x)
y1 = np.sin(2*x) + 2
y2 = np.sin(4*x) + 4
y3 = np.sin(8*x) + 6 y4
'--r')
plt.plot(x, y1, '--b')
plt.plot(x, y2, '--g')
plt.plot(x, y3, '--m') plt.plot(x, y4,