import matplotlib.pyplot as plt
import numpy as np
import warnings
warnings.filterwarnings('ignore')
# 전형적인 classic 스타일을 선택했다.
# 더 많은 스타일은 https://matplotlib.org/gallery/style_sheets/style_sheets_reference.html 여기를 참고.
plt.style.use('classic')
x = np.linspace(0, 10, 100)
display(x)
# cos 함수, sin 함수를 그려본다.
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
# show 명령어는 시스템의 대화형 그래픽 벡엔드와 상호작용을해야 하기 때문에 내부에서 많은 작업을 수행한다.
plt.show()
array([ 0. , 0.1010101 , 0.2020202 , 0.3030303 , 0.4040404 , 0.50505051, 0.60606061, 0.70707071, 0.80808081, 0.90909091, 1.01010101, 1.11111111, 1.21212121, 1.31313131, 1.41414141, 1.51515152, 1.61616162, 1.71717172, 1.81818182, 1.91919192, 2.02020202, 2.12121212, 2.22222222, 2.32323232, 2.42424242, 2.52525253, 2.62626263, 2.72727273, 2.82828283, 2.92929293, 3.03030303, 3.13131313, 3.23232323, 3.33333333, 3.43434343, 3.53535354, 3.63636364, 3.73737374, 3.83838384, 3.93939394, 4.04040404, 4.14141414, 4.24242424, 4.34343434, 4.44444444, 4.54545455, 4.64646465, 4.74747475, 4.84848485, 4.94949495, 5.05050505, 5.15151515, 5.25252525, 5.35353535, 5.45454545, 5.55555556, 5.65656566, 5.75757576, 5.85858586, 5.95959596, 6.06060606, 6.16161616, 6.26262626, 6.36363636, 6.46464646, 6.56565657, 6.66666667, 6.76767677, 6.86868687, 6.96969697, 7.07070707, 7.17171717, 7.27272727, 7.37373737, 7.47474747, 7.57575758, 7.67676768, 7.77777778, 7.87878788, 7.97979798, 8.08080808, 8.18181818, 8.28282828, 8.38383838, 8.48484848, 8.58585859, 8.68686869, 8.78787879, 8.88888889, 8.98989899, 9.09090909, 9.19191919, 9.29292929, 9.39393939, 9.49494949, 9.5959596 , 9.6969697 , 9.7979798 , 9.8989899 , 10. ])
plt.show()
파이썬 세션당 한 번만 사용할 수 있어서 대체로 스크립트의 맨 마지막에 사용된다.%matplotlib
명령어를 사용하면 된다.show()
함수를 사용하지 않아도 된다.%matplotlib
Using matplotlib backend: MacOSX
# 노트북에 플롯의 정적 이미지를 삽입할 수 있다. 커널/세션당 한 번만 실행하면 된다.
%matplotlib inline
x = np.linspace(0, 10, 100)
# 해당 plot을 사진 파일로 저장할 때 사용할 것이다.
fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--')
[<matplotlib.lines.Line2D at 0x120fb8390>]
fig.savefig('my_figure.png')
# 이 명령어를 실행하면, 그림 파일이 저장된 것을 확인할 수 있다. !는 리눅스 명령어 모드로 진입할 수 있도록 해주는 것.
!ls -lh my_figure.png
-rw-r--r-- 1 yoonjeonghun staff 26K 2 28 23:17 my_figure.png
# 외부에 있던 파일을 호출해서 표시해보자.
from IPython.display import Image
Image('my_figure.png')
# 저장 가능한 파일의 종류는 무엇이 있을까?
fig.canvas.get_supported_filetypes()
{'ps': 'Postscript', 'eps': 'Encapsulated Postscript', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}
Matplotlib
은 원래 매트랩(MATLAB) 사용자를 위한 파이썬 대안으로 제작됐으며, Matplotlib
이 제공하는 구문의 대부분이 그 사실을 반영한다."""매트랩 사용자들에게 친숙해보이는 코드"""
# 플롯 그림을 생성
plt.figure()
# 두 개의 패널 중 첫 번째 패널을 생성하고 현재 축(axis)을 설정
plt.subplot(2, 1, 1)
plt.plot(x, np.sin(x))
# 두 번째 패널을 생성하고 현재 축(axis)을 설정
plt.subplot(2, 1, 2)
plt.plot(x, np.cos(x))
[<matplotlib.lines.Line2D at 0x123f3a0b8>]
Figure
와 Axes
객체의 메서드이다.# 먼저 플롯 그리드를 생성
# ax는 두 개의 축 객체의 배열이 된다.
fig, ax = plt.subplots(2)
# 적절한 객체에서 plot() 메서드를 호출
ax[0].plot(x, np.sin(x))
ax[1].plot(x, np.cos(x))
[<matplotlib.lines.Line2D at 0x124096ba8>]
# 스타일을 변경하자.
plt.style.use('seaborn-whitegrid')
plt.Figure
클래스의 인스턴스 : 축, 그래픽, 텍스트, 레이블을 표시하는 모든 객체를 포함하는 하나의 컨테이너로 생각하면 된다.plt.Axes
클래스의 인스턴스 : 눈금과 레이블이 있는 테두리 상자로 나중에 시각화를 형성하는 플롯 요소를 포함하게 된다.# 그림(figure)과 축(axes)을 만드는 명령어
fig = plt.figure()
ax = plt.axes()
# 간단한 Sin 곡선으로 플로팅을 시작해보자.
x = np.linspace(0, 10, 1000)
plt.plot(x, np.sin(x))
[<matplotlib.lines.Line2D at 0x124225e10>]
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
[<matplotlib.lines.Line2D at 0x1241a9198>]
"""색상을 변경하는 다양한 방법 1"""
plt.plot(x, np.sin(x - 0), color='blue')
plt.plot(x, np.sin(x - 1), color='g')
plt.plot(x, np.sin(x - 2), color='0.75')
[<matplotlib.lines.Line2D at 0x12439bf28>]
"""색상을 변경하는 다양한 방법 2"""
plt.plot(x, np.sin(x - 0), color='#FFDD44')
plt.plot(x, np.sin(x - 1), color=(1.0, 0.2, 0.3))
plt.plot(x, np.sin(x - 2), color='chartreuse')
[<matplotlib.lines.Line2D at 0x12446a358>]
"""선 스타일을 조정하는 다양한 방법 1"""
plt.plot(x, x + 0, linestyle='solid')
plt.plot(x, x + 1, linestyle='dashed')
plt.plot(x, x + 2, linestyle='dashdot')
plt.plot(x, x + 3, linestyle='dotted')
[<matplotlib.lines.Line2D at 0x12451ae48>]
"""선 스타일을 조정하는 다양한 방법 2"""
plt.plot(x, x + 0, linestyle='-') # solid
plt.plot(x, x + 1, linestyle='--') # dashed
plt.plot(x, x + 2, linestyle='-.') # dashdot
plt.plot(x, x + 3, linestyle=':') # dotted
[<matplotlib.lines.Line2D at 0x12458c630>]
"""색상과 선 스타일을 동시에 조정하는 다양한 방법 2"""
plt.plot(x, x + 0, '-g') # solid green
plt.plot(x, x + 1, '--c') # dashed cyan
plt.plot(x, x + 2, '-.k') # dashdot black
plt.plot(x, x + 3, ':r') # dotted red
[<matplotlib.lines.Line2D at 0x1246b2550>]
plt.xlim()
과 plt.ylim()
메서드를 사용하는 것.plt.plot(x, np.sin(x))
display(plt.xlim(-1, 11))
display(plt.ylim(-1.5, 1.5))
(-1, 11)
(-1.5, 1.5)
plt.plot(x, np.sin(x))
display(plt.xlim(10, 0))
display(plt.ylim(1.2, -1.2))
(10, 0)
(1.2, -1.2)
plt.axis()
는 현재 플롯 주변의 경계를 자동으로 더 밀착시켜준다.plt.plot(x, np.sin(x))
plt.axis('tight')
(0.0, 10.0, -0.9999972954811321, 0.9999996994977832)
x
축의 한 단위와 y
축의 한 단위가 똑같게 설정plt.plot(x, np.sin(x))
plt.axis('equal')
(0.0, 10.0, -1.0, 1.0)
plt.plot(x, np.sin(x))
plt.title("A Sine Curve")
plt.xlabel("x")
plt.ylabel("sin(x)")
Text(0,0.5,'sin(x)')
# 곡선별로 라벨링을 한다.
plt.plot(x, np.sin(x), '-g', label='sin(x)')
plt.plot(x, np.cos(x), ':b', label='cos(x)')
# x, y의 간격을 동일하게한다.
plt.axis('equal')
# 라인 스타일과 색상을 기록하고 이를 정확한 레이블과 매칭하도록 하는 메서드.
plt.legend()
<matplotlib.legend.Legend at 0x124b30320>
x = np.linspace(0, 10, 30)
y = np.sin(x)
# 산점도 표현을 위해 plot의 입력인수를 'o'로 한다.
plt.plot(x, y, 'o', color='black')
[<matplotlib.lines.Line2D at 0x124bfb5c0>]
rng = np.random.RandomState(0)
for maker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
plt.plot(rng.rand(5), rng.rand(5), maker, label="maker='{0}'".format(maker))
plt.legend(numpoints=1)
plt.xlim(0, 1.8)
# 더 간단하게 나타내는 방법
# 선(-), 원 표시 기호(o), 검정색(k)
plt.plot(x, y, '-ok')
[<matplotlib.lines.Line2D at 0x124e2ab00>]
# 다양한 선과 표시 속성을 지정
# p : 오각형
plt.plot(x, y, '-p', color='gray', markersize=15, linewidth=4,
markerfacecolor='white', markeredgecolor='gray', markeredgewidth=2)
plt.ylim(-1.2, 1.2)
(-1.2, 1.2)
plt.scatter(x, y, marker='o')
<matplotlib.collections.PathCollection at 0x124ed22b0>
plt.scatter()
의 경우 각 점의 속성(크기, 표면 색상, 테두리 색상 등)을 개별적으로 제어하거나 데이터에 매핑할 수 있는 산점도를 만드는데 사용할 수 있다.rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3, cmap='viridis')
# 색상 척도 표시 - 다차원 데이터를 표시하기 위해 점의 색상과 크기를 사용해 정보를 전달 할 수 있다.
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x124d27be0>
"""Scikit-Learn에서 제공하는 붓꽃 데이터를 사용해보자.
이 데이터에서 각 표본은 세 가지 유형의 꽃 중 하나로 그 꽃잎과
꽃받침의 크기를 세밀하게 측정한 값을 가지고 있다."""
from sklearn.datasets import load_iris
iris = load_iris()
features = iris.data.T
plt.scatter(features[0], features[1], alpha=0.2,
s=100*features[3], c=iris.target, cmap='viridis')
plt.xlabel(iris.feature_names[0])
plt.xlabel(iris.feature_names[1])
Text(0.5,0,'sepal width (cm)')
plt.plot
이 plt.scatter
보다 확실히 더 효율적이다.plt.scatter
는 각 점에 대한 다양한 크기와 색상을 나타내는 능력이 있어서 렌더러가 각 점을 개별적으로 구성하는 추가 작업을 해야 하기 때문이다.plt.plot
에서는 점이 기본적으로 항상 서로 복제되므로 점의 모양을 결정하는 작업이 전체 데이터에 대해 한 번만 수행된다.errorbar
)¶plt.style.use('seaborn-whitegrid')
x = np.linspace(0, 10, 50)
dy = 0.8
# 오차를 일부러 준 상황
y = np.sin(x) + dy *np.random.randn(50)
# 오차구간을 0.8을 준다.
# 선과 점의 모양을 제어하는 포맷 코드
plt.errorbar(x, y, yerr=dy, fmt='.k')
<Container object of 3 artists>
# errorbar의 색깔 및 면적을 조절한다.
plt.errorbar(x, y, yerr=dy, fmt='o', color='black', ecolor='lightgray', elinewidth=3, capsize=0)
<Container object of 3 artists>
plt.style.use('seaborn-white')
# 3차원 공간에 정의되는 함수를 정의한다.
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
"""plt.contour는 x값의 격자, y값의 격자, z값의 격자라는 세 개의 인수를 취한다."""
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
# 1차 배열로부터 2차원 그리드를 만든다.
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
display(X)
display(Y)
array([[0. , 0.10204082, 0.20408163, ..., 4.79591837, 4.89795918, 5. ], [0. , 0.10204082, 0.20408163, ..., 4.79591837, 4.89795918, 5. ], [0. , 0.10204082, 0.20408163, ..., 4.79591837, 4.89795918, 5. ], ..., [0. , 0.10204082, 0.20408163, ..., 4.79591837, 4.89795918, 5. ], [0. , 0.10204082, 0.20408163, ..., 4.79591837, 4.89795918, 5. ], [0. , 0.10204082, 0.20408163, ..., 4.79591837, 4.89795918, 5. ]])
array([[0. , 0. , 0. , ..., 0. , 0. , 0. ], [0.12820513, 0.12820513, 0.12820513, ..., 0.12820513, 0.12820513, 0.12820513], [0.25641026, 0.25641026, 0.25641026, ..., 0.25641026, 0.25641026, 0.25641026], ..., [4.74358974, 4.74358974, 4.74358974, ..., 4.74358974, 4.74358974, 4.74358974], [4.87179487, 4.87179487, 4.87179487, ..., 4.87179487, 4.87179487, 4.87179487], [5. , 5. , 5. , ..., 5. , 5. , 5. ]])
# 선으로만 구성된 표준 등고선 플롯을 그린다.
# 단색이 사용되면 음수 값은 점선으로 양수 값은 실선으로 표시된다.
plt.contour(X, Y, Z, colors='black')
<matplotlib.contour.QuadContourSet at 0x1a26e881d0>
# 색상표를 지정해 선에 색을 입힌다.
# RdGy : RedGray의 약어
plt.contour(X, Y, Z, 20, cmap='RdGy')
<matplotlib.contour.QuadContourSet at 0x1a26f464e0>
"""색으로 채워진 등고선 플롯으로 바꾸기"""
plt.contourf(X, Y, Z, 20, cmap='RdGy')
<matplotlib.contour.QuadContourSet at 0x110736b00>
# 색상 단계가 연속적이 아니라 불연속적으로 보이는 것을 해결하기.
# imshow 메서드는 x와 y그리드를 받지 않으므로 플롯에 이미지의 extent[xmin, xmax, ymin, ymax]
# imshow 메서드는 입력 데이터를 매칭하기 위해 자동으로 축의 가로세로 비율을 조정한다.
# axis(aspect=)를 이용해 x와 y의 단위를 일치시킬 수 있다.
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower', cmap='RdGy')
plt.colorbar()
plt.axis(aspect='image')
(0.0, 5.0, 0.0, 5.0)
"""등고선 플롯과 이미지 플롯을 결합하는 경우"""
contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower', cmap='RdGy', alpha=0.5)
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x1a2726aeb8>
import matplotlib as mpl
# Default settings
mpl.rcParams.update(mpl.rcParamsDefault)
# 간단하게 지수분포를 그려보자.
x = np.arange(0, 1, 0.01)
y = np.exp(x)
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
Text(0,0.5,'Y')
Size 조절 :
plt.rcParams
사용
# plt의 rcParams를 사용한다.
plt.rcParams["figure.figsize"] = (20,3)
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
Text(0,0.5,'Y')
Font 조절 (https://matplotlib.org/users/text_props.html?highlight=configuring%20font%20family)
matplotlib.rc
사용mpl.rcParams.update(mpl.rcParamsDefault)
# matplotlib.rc를 이용하여, dictinary를 주입
font = {'family' : 'fantasy',
'weight' : 'bold',
'size' : 22}
mpl.rc('font', **font)
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
Text(0,0.5,'Y')
mpl.rcParams.update(mpl.rcParamsDefault)
MEDIUM_SIZE = 20
BIGGER_SIZE = 30
mpl.rc('xtick', labelsize=MEDIUM_SIZE)
mpl.rc('ytick', labelsize=BIGGER_SIZE)
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
Text(0,0.5,'Y')