작성일자 : 2024-09-21
수정일자 : 2024-09-26
Ver 0.1.2
Matplotlib 해부도
subplot() 이용
import matplotlib.pyplot as plt
plt.subplot(<rows>, <columns>, 1)
(데이터, 서식 etc)
plt.<parameter>()
...
plt.subplot(<rows>, <columns>, 2)
(데이터, 서식 etc)
plt.<parameter>()
...
plt.subplot(<rows>, <columns>, <index>)
(데이터, 서식 etc)
plt.<parameter>()
...
plt.show()
stateless API (objected-based) 이용
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(<rows>, <columns>, 1)
(데이터, 서식 etc)
ax.<parameter>()
...
ax = fig.add_subplot(<rows>, <columns>, 2)
(데이터, 서식 etc)
ax.<parameter>()
...
ax = fig.add_subplot(<rows>, <columns>, <index>)
(데이터, 서식 etc)
ax.<parameter>()
...
plt.show()
예제)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
fig = plt.figure(figsize=(6,5))
fig.set_facecolor("skyblue")
ax = fig.add_subplot(1,2,1)
ax.set_facecolor("blue")
ax.plot(x,y)
ax = fig.add_subplot(1,2,2)
ax.set_facecolor("yellow")
subplots()
import matplotlib.pyplot as plt
fig, ax = plt.figure(<rows>, <columns>)
# 방법1
(데이터, 서식 etc)
ax[0].<parameter>()
...
(데이터, 서식 etc)
ax[1].<parameter>()
...
plt.show()
# 방법2
(데이터, 서식 etc)
ax[0,0].<parameter>()
...
(데이터, 서식 etc)
ax[0,1].<parameter>()
...
plt.show()
예제1)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
fig, axs = plt.subplots(2,2, figsize=(6, 6))
fig.set_facecolor('skyblue')
axs[0,0].set_facecolor('green')
axs[0,0].plot(x,y,color = 'white')
axs[0,1].set_facecolor('blue')
axs[1,0].set_facecolor('yellow')
axs[1,1].set_facecolor('red')
예제2)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
fig, (ax1, ax2) = plt.subplots(1,2, figsize = (6,4))
fig.set_facecolor("skyblue")
ax1.set_facecolor("blue")
ax1.plot(x,y)
ax2.set_facecolor("yellow")
subplots2grid
그래프 별로 크기를 달리 하고 싶을 때 적용할 수 있는 방법이다.
matplotlib.pyplot.subplot2grid(shape # (<int>, <int>) : Number of rows and of columns of the grid in which to place axis.
,loc # (<int>, <int>) : Row number and column number of the axis location within the grid.
,rowspan = <number> # defualt = 1, Number of rows for the axis to span downwards.
,colspan = <number> # defualt = 1, Number of columns for the axis to span to the right.
,fig = None # optional, Figure to place the subplot in. Defaults to the current figure.
,**kwargs) # Additional keyword arguments are handed to add_subplot.
예제)
import matplotlib.pyplot as plt
import numpy as np
# create plot and set location
fig = plt.figure()
axs1 = plt.subplot2grid((3,3), (0,0), colspan = 2) # Top Left (0,0), merge 2 columns in 3x3 space
axs2 = plt.subplot2grid((3,3), (1,0), rowspan = 2, colspan = 2) # Top Left (1,0), merge 2 rows and columns in 3x3 space
axs3 = plt.subplot2grid((3,3), (0,2), rowspan = 3) # Top Left (0,2), merge 3 rows in 3x3 space
fig.set_facecolor('lightgray')
# graph 1 : y = x * x
x = np.arange(1,10)
axs1.plot(x, x*x)
axs1.set_title('x*x')
axs1.grid()
# graph 2 : box plot
axs2.boxplot(np.random.randn(500,5))
axs2.set_facecolor('#E6F0F8')
axs2.set_title('box plot')
# graph 3 : y = x ** 3
x = np.arange(1,10)
axs3.plot(x, x ** 3)
axs3.set_title('x ** 3')
axs3.grid(color = 'b', ls = '-.', lw = 0.75) # blue, dot-line, linewidth = 0.75
plt.tight_layout() # input appropriate padding automatically
plt.show()
add_gridspec
그래프 별로 크기를 달리 하고 싶을 때 적용할 수 있고, 좀 더 정밀하게 사이즈를 조절할 수 있고, seaborn까지 활용할 수 있다.
import warnings
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
# figure 생성
fig = plt.figure(figsize=(20, 12))
# 상단 그리드 설정 (nrows=1, ncols=1)
gs1_nrows = 1
gs1_ncols = 1
gs1 = fig.add_gridspec(nrows = gs1_nrows, ncols = gs1_ncols, left = 0, bottom = 0.6, top = 1)
# 상단 subplot
ax1 = fig.add_subplot(gs1[0, 0])
game_events_sample_top20 = game_events_sample.head()
sns.countplot(data = game_events_sample, x = 'event', ax = ax1)
ax1.set_title('Event Frequency in Game Event')
ax1.set_xticks(ax1.get_xticks()) # xticks 추가 (회전 적용)
ax1.set_xticklabels(ax1.get_xticklabels(), rotation=60)
ax1.set_xlabel('')
# 하단 그리드 설정 (nrows=1, ncols=2)
gs2_nrows = 1
gs2_ncols = 2
gs2 = fig.add_gridspec(nrows = gs2_nrows, ncols = gs2_ncols, left = 0, bottom = 0, top = 0.5)
# 하단 왼쪽 subplot (첫 번째 subplot)
ax2 = fig.add_subplot(gs2[0, 0])
sns.barplot(data = game_events_sample, x = 'faction', y = 'num', estimator = sum, ax = ax2)
ax2.set_title('Total Event Values by Faction')
ax2.set_xticks(ax2.get_xticks()) # xticks 추가 (회전 적용)
ax2.set_xticklabels(ax2.get_xticklabels(), rotation=60)
ax2.set_xlabel('')
# 하단 오른쪽 subplot (두 번째 subplot)
ax3 = fig.add_subplot(gs2[0, 1])
round_event_count = game_events_sample.groupby('round').size().reset_index(name='counts')
sns.lineplot(data = round_event_count, x = 'round', y = 'counts', marker='o')
plt.title('Event Frequency by Round')
plt.xlabel('Round')
plt.ylabel('Event Frequency')
plt.grid(True)
plt.tight_layout()
plt.show()
# 레이아웃 최적화
fig.tight_layout()
# 그래프 출력
plt.show()
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure(figsize=(12,7))
widths = [4, 4, 1]
heights = [1, 4]
### 1. gridspec preparation
spec = fig.add_gridspec(ncols=3, nrows=2, width_ratios=widths, height_ratios=heights)
### 2. setting axes
axs = {}
for i in range(len(heights)*len(widths)):
axs[i] = fig.add_subplot(spec[i//len(widths), i%len(widths)])
axs[i].text(0.5, 0.5, f"axs[{i}]", fontdict={"horizontalalignment":"center", "color":"gray"})
참고 사이트