> For the complete documentation index, see [llms.txt](https://sangmandu.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sangmandu.gitbook.io/til/til_ml/boostcamp-2st/s-data-viz/3-3-facet.md).

# (3-3) Facet 사용하기

## 1. Facet

Facet이란 분할을 의미한다. 화면상에 View를 분할 및 추가하여 다양한 관점을 전달할 수 있다.

* 같은 데이터셋에 서로 다른 인코딩을 통해 다른 인사이트를 제공
* 같은 방법으로 동시에 여러 feature를 볼 수 있음
* 큰 틀에서 볼 수 없는 부분 집합을 세세하게 보여줄 수 있음

## 2. Matplotlib에서 구현

### 2.1 Figure와 Axes

![](/files/-MhqMspqHD96tuAU2LNI)

* Figure는 큰 틀, Ax는 각 플롯이 들어가는 공간이다.
* 따라서, Figure는 항상 1개, 플롯은 사용자가 정한 n개이다.

### 2.2 NxM subplots

가장 쉬운 방법 3가지

* plt.subplot()
* plt.figure() + fig.add\_subplot()
* plt.subplots()

쉽게 조정할 수 있는 요소

* figuresize
* dpi
* sharex, sharey
* squeeze
* aspect

### 2.3 Grid Spec

![](/files/-MhqN_ElHeUJN92u_z5W)

위 서브플롯을 표현하기 위한 2가지 방법이 있다

* Slicing 사용
  * 💙 : axes\[0, :3]
  * 💛 : axes\[1:, :3]
  * 💜 : axes\[3, :]
  * fig.add\_grid\_spec()
* x, y, dx, dy를 사용
  * 💙 : (0, 0), 1, 3
  * 💛 : (1, 0), 3, 3
  * 💜 : (0, 3), 1, 4
  * fig.subplot2grid()

### 2.4 내부에 그리기

<div align="left"><img src="/files/-MhqNy5EAY7-IZB-Muqz" alt=""></div>

* ax.inset\_axes()
  * Ax내부에 서브플롯을 추가하여 외부 정보를 적은 비중으로 위치시킬 수 있다.

### 2.5 외부에 그리기

<div align="left"><img src="/files/-MhqO8ndzp5KR69K5Ma1" alt=""></div>

* make\_axes\_locatable(ax)
  * 그리드를 사용하지 않고 사이드에 추가하는 방법으로 방향의 통계정보나 제목 등의 텍스트를 추가할 수 있다.

## 3-3-Facet <a href="#id-3-3-facet" id="id-3-3-facet"></a>

### 1. Figure & Subplots <a href="#id-1.-figure-and-subplots" id="id-1.-figure-and-subplots"></a>

#### 1-1. Figure & Axes <a href="#id-1-1.-figure-and-axes" id="id-1-1.-figure-and-axes"></a>

**1-3. Python과 Matplotlib** 에서 이미 살펴보았기에 가볍게만 보겠습니다.

```python
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
```

```python
fig = plt.figure()
ax = fig.add_subplot(121)
ax = fig.add_subplot(122)
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FvMjl0RcTija6Mdv72eah%2Ffile.png?alt=media)

```python
fig, (ax1, ax2) = plt.subplots(1, 2)
# 또는 fig, axes로 받고, axes[0]으로 접근하는 방법도 있다
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FM50fqCXDPNffNQ9iHSrV%2Ffile.png?alt=media)

#### 1-2. Figure Color <a href="#id-1-2.-figure-color" id="id-1-2.-figure-color"></a>

하얀 배경의 내용일 떄 차트와 배경을 구분하기 위해 차트 배경 색을 조정할 수 있습니다.

```python
fig, ax = plt.subplots()
# fig.set-facecolor로 바꿀 수도 있고 figure를 선언할 때 color인자로 바꿀 수도 있다.
fig.set_facecolor('lightgray')
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FhPQkKqDXYJ1F1FV4dsLP%2Ffile.png?alt=media)

### 2. Figure & Ax Properties <a href="#id-2.-figure-and-ax-properties" id="id-2.-figure-and-ax-properties"></a>

#### 2-1. DPI <a href="#id-2-1.-dpi" id="id-2-1.-dpi"></a>

* `dpi` : Dots per Inch

DPI는 인치에 해당하는 dot 수를 정하는 인자로 해상도를 의미합니다. 기본값은 100입니다.

150, 200, 300 값 등을 조정하며 원하는 해상도로 출력할 수 있습니다.

```python
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax1.plot([1, 2, 3], [1, 4, 9])
ax2.plot([1, 2, 3], [1, 2, 3])
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FSb1FvgP2p7S9ZJMhV7th%2Ffile.png?alt=media)

```
fig = plt.figure(dpi=150)
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax1.plot([1, 2, 3], [1, 4, 9])
ax2.plot([1, 2, 3], [1, 2, 3])
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FrTKqOCQzXH8FK22YQ5bK%2Ffile.png?alt=media)

```python
fig.savefig('file_name', dpi=150)
```

* 이 함수를 이용해 원하는 해상도로 fig를 저장할 수 있다.
* 노트북과 같은 디렉토리에 파일이 저장된다.

#### 2-2. Sharex, Sharey <a href="#id-2-2.-sharex-sharey" id="id-2-2.-sharex-sharey"></a>

* `sharex`, `sharey`

개별 ax에 대해서나 `subplots` 함수를 사용할 때는 `sharex`, `sharey`를 사용하여 축을 공유할 수 있습니다.

```python
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.plot([1, 2, 3], [1, 4, 9])
ax2 = fig.add_subplot(122, sharey=ax1)
ax2.plot([1, 2, 3], [1, 2, 3])
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FZTpGJcujAgnbG9ZYdvHY%2Ffile.png?alt=media)

```
fig, axes = plt.subplots(1, 2, sharey=True)

axes[0].plot([1, 2, 3], [1, 4, 9])
axes[1].plot([1, 2, 3], [1, 2, 3])
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FK1aCvYUmZDyEeXjokSpu%2Ffile.png?alt=media)

`fig.add_subplot` 의 `sharex` 또는 `sharey` 인자로 공유할 `ax`를 선택할 수도 있고 `plt.subplots` 으로 초기에 `fig`를 생성할 때 이 값을 `True` 로 설정하면서 공유할 수도 있다.

#### 2-3. squeeze와 flatten <a href="#id-2-3.-squeeze-flatten" id="id-2-3.-squeeze-flatten"></a>

* `squeeze`

`subplots()`로 생성하면 기본적으로 다음과 같이 서브플롯 ax 배열이 생성됩니다.

* 1 x 1 : 객체 1개 (`ax`)
* 1 x N 또는 N x 1 : 길이 N 배열 (`axes[i]`)
* N x M : N by M 배열 (`axes[i][j]`)

numpy ndarray에서 각각 차원이 0, 1, 2로 나타납니다. 이렇게 되면 경우에 따라 반복문을 사용할 수 있거나, 없거나로 구분됩니다.

`squeeze`를 사용하면 항상 2차원으로 배열을 받을 수 있고, 가변 크기에 대해 반복문을 사용하기에 유용합니다.

```python
n, m = 1, 3

fig, axes = plt.subplots(n, m, squeeze=False, figsize=(m*2, n*2))
idx = 0
for i in range(n):
    for j in range(m):
        axes[i][j].set_title(idx)
        axes[i][j].set_xticks([])
        axes[i][j].set_yticks([])
        idx+=1

plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FvMaMMBzeHSvEmSRLxwqV%2Ffile.png?alt=media)

`plt.subplots()`나 `plt.gca()`로 받는 ax 리스트는 numpy ndarray로 전달됩니다.

그렇기에 1중 반복문을 쓰고 싶다면 `flatten()` 메서드를 사용할 수 있습니다.

```python
n, m = 2, 3

fig, axes = plt.subplots(n, m, figsize=(m*2, n*2))

for i, ax in enumerate(axes.flatten()):
    ax.set_title(i)
    ax.set_xticks([])
    ax.set_yticks([])


plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FX1LEBgWKQENv1GPVkDOO%2Ffile.png?alt=media)

#### 2-4. aspect <a href="#id-2-4.-aspect" id="id-2-4.-aspect"></a>

* `aspect`

```python
fig = plt.figure(figsize=(12, 5))
ax1 = fig.add_subplot(121, aspect=1)
ax2 = fig.add_subplot(122, aspect=0.5)
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2F6PbPrJYZhOCghb2SU83A%2Ffile.png?alt=media)

```python
fig = plt.figure(figsize=(12, 5))
ax1 = fig.add_subplot(121, aspect=1)
ax2 = fig.add_subplot(122, aspect=0.5)

ax2.set_xlim(0, 1)
ax2.set_ylim(0, 2)
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2F4koD9vO8FO4NLulv0yo6%2Ffile.png?alt=media)

### 3. Gridspec <a href="#id-3.-gridspec" id="id-3.-gridspec"></a>

#### 3-1. add\_gridspec <a href="#id-3-1.-add_gridspec" id="id-3-1.-add_gridspec"></a>

N by M 그리드에서 슬라이싱으로 서브플롯을 배치할 수 있습니다.

```python
fig = plt.figure(figsize=(8, 5))

gs = fig.add_gridspec(3, 3) # make 3 by 3 grid (row, col)

ax = [None for _ in range(5)]

ax[0] = fig.add_subplot(gs[0, :]) 
ax[0].set_title('gs[0, :]')

ax[1] = fig.add_subplot(gs[1, :-1])
ax[1].set_title('gs[1, :-1]')

ax[2] = fig.add_subplot(gs[1:, -1])
ax[2].set_title('gs[1:, -1]')

ax[3] = fig.add_subplot(gs[-1, 0])
ax[3].set_title('gs[-1, 0]')

ax[4] = fig.add_subplot(gs[-1, -2])
ax[4].set_title('gs[-1, -2]')

for ix in range(5):
    ax[ix].set_xticks([])
    ax[ix].set_yticks([])

plt.tight_layout()
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2F3zd0QECdhlaf1tqPGRQU%2Ffile.png?alt=media)

#### 3-2. subplot2grid <a href="#id-3-2.-subplot2grid" id="id-3-2.-subplot2grid"></a>

N x M 그리드에서 시작점에서 delta x, delta y로 표현할 수 있습니다.

> 개인적으로는 add\_gridspec을 더 선호합니다.

```python
fig = plt.figure(figsize=(8, 5)) # initialize figure

ax = [None for _ in range(6)] # list to save many ax for setting parameter in each

ax[0] = plt.subplot2grid((3,4), (0,0), colspan=4)
ax[1] = plt.subplot2grid((3,4), (1,0), colspan=1)
ax[2] = plt.subplot2grid((3,4), (1,1), colspan=1)
ax[3] = plt.subplot2grid((3,4), (1,2), colspan=1)
ax[4] = plt.subplot2grid((3,4), (1,3), colspan=1,rowspan=2)
ax[5] = plt.subplot2grid((3,4), (2,0), colspan=3)


for ix in range(6): 
    ax[ix].set_title('ax[{}]'.format(ix)) # make ax title for distinguish:)
    ax[ix].set_xticks([]) # to remove x ticks
    ax[ix].set_yticks([]) # to remove y ticks
    
fig.tight_layout()
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FbzqQ0DGmfE65jnFhKJxt%2Ffile.png?alt=media)

#### 3-3. add\_axes <a href="#id-3-3.-add_axes" id="id-3-3.-add_axes"></a>

특정 플롯을 임의의 위치에 만드는 메서드입니다.

위치를 조정하여 그래프를 그리는 게 쉽지는 않기 때문에 추천하지 않습니다.

```python
fig = plt.figure(figsize=(8, 5))

ax = [None for _ in range(3)]


ax[0] = fig.add_axes([0.1,0.1,0.8,0.4]) # x, y, dx, dy
ax[1] = fig.add_axes([0.15,0.6,0.25,0.6])
ax[2] = fig.add_axes([0.5,0.6,0.4,0.3])

for ix in range(3):
    ax[ix].set_title('ax[{}]'.format(ix))
    ax[ix].set_xticks([])
    ax[ix].set_yticks([])

plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FWdoqCJqo1eAPTH2mTHZR%2Ffile.png?alt=media)

#### 3-4. inset\_axes <a href="#id-3-4.-inset_axes" id="id-3-4.-inset_axes"></a>

미니맵 등 원하는 서브플롯을 그릴 때 사용할 수 있습니다.

표현하고자 하는 메인시각화를 해치지 않는 선에서 사용하는 것을 추천합니다.

```python
fig, ax = plt.subplots()
axin = ax.inset_axes([0.8, 0.8, 0.2, 0.2])
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2Fiegg0qGAqLuN2Q4EwX43%2Ffile.png?alt=media)

```python
fig, ax = plt.subplots()

color=['royalblue', 'tomato']
ax.bar(['A', 'B'], [1, 2],
       color=color
      )

ax.margins(0.2)
axin = ax.inset_axes([0.8, 0.8, 0.2, 0.2])
axin.pie([1, 2], colors=color, 
         autopct='%1.0f%%')
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FLC4IMKSg3M9jZazc6KM4%2Ffile.png?alt=media)

#### 3-5. make\_axes\_locatable <a href="#id-3-5.--make_axes_locatable" id="id-3-5.--make_axes_locatable"></a>

일반적으로 colorbar에 많이 사용합니다.

```python
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable

fig, ax = plt.subplots(1, 1)
ax_divider = make_axes_locatable(ax)

ax = ax_divider.append_axes("right", size="7%", pad="2%")
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FyHgXoqx0DfNKDkfyzjXi%2Ffile.png?alt=media)

```python
fig, ax = plt.subplots(1, 1)

# 이미지를 보여주는 시각화
# 2D 배열을 색으로 보여줌
im = ax.imshow(np.arange(100).reshape((10, 10)))

divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

fig.colorbar(im, cax=cax)
plt.show()
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MNN4u9o9noCQwX8pO35%2Fuploads%2FksZVF6hHQuYVeITVQc1v%2Ffile.png?alt=media)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sangmandu.gitbook.io/til/til_ml/boostcamp-2st/s-data-viz/3-3-facet.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
