파이썬/시각화 matplot

[matplot] axes를 행,열로 쪼개어 서브플롯 그리기- subplots

Merware 2023. 5. 15. 16:41

[학습목표]
axes를 행,열로 쪼개어 서브플롯을 그릴 수 있다.

import matplotlib.pyplot as plt

 

데이터 불러오기

import seaborn as sns
anscombe = sns.load_dataset('anscombe')
df1 = anscombe[anscombe['dataset']=='I']
df2 = anscombe[anscombe['dataset']=='II']
df3 = anscombe[anscombe['dataset']=='III']
df4 = anscombe[anscombe['dataset']=='IV']

df4.head(1)

"""
	dataset	x	y
33	IV	8.0	6.58

 

axes를 행, 열로 쪼개어 서브플롯 그리기

  • plt.subplots() 함수를 호출하면 figure, axes 객체를 생성하여 튜플 형태로 반환한다.
    fig, ax = plt.subplots()

    1) axes 객체를 행,열로 쪼개어 생성하기
    fig, ax = plt.subplots(nrows=행개수, ncols=열개수,figsize=(가로사이즈,세로사이즈))

    2) axes[행번호][열번호] 형태로 접근하여 그래프 그리기
    3) 서브플롯간 축을 공유할 수 있다.
    sharex=True, sharey=True
# 1) axes 객체를 행,열로 쪼개어 생성하기
# 3) 서브플롯간 축을 공유할 수 있다.
fig,ax = plt.subplots(nrows=2, ncols=2, figsize=(8,6), sharex=True, sharey=True)

# 2) axes[행번호][열번호] 형태로 접근하여 그래프 그리기
ax[0][0].plot(df1['x'],df1['y'],'o')
ax[0][1].plot(df2['x'],df2['y'],'^')
ax[1][0].plot(df3['x'],df3['y'],'*')
ax[1][1].plot(df4['x'],df4['y'],'d')

# 4) 각 그래프에 제목 추가
ax[0][0].set_title('ax1')
ax[0][1].set_title('ax2')
ax[1][0].set_title('ax3')
ax[1][1].set_title('ax4')

# 4) 각 그래프에 그리드 추가
ax[0][0].grid(ls=':')
ax[0][1].grid(ls=':', color='pink')
ax[1][0].grid(ls=':', color='skyblue')
ax[1][1].grid(ls=':', color='green', alpha=0.5)

# 6) 그래프 전체 제목
fig.suptitle('Anscombe', size=20)

# 7) 그래프 간격, 크기 최적화
fig.tight_layout()