파이썬/시각화 matplot

[matplot] 전체 행 열과 그래프 순서에 따라 서브플롯 그리기 - add_subplot

Merware 2023. 5. 15. 17:34

[학습목표]
전체 행 열과 그래프 순서를 지정하여 서브플롯을 그릴 수 있다.

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

"""
	dataset	x	y
33	IV	8.0	6.58
34	IV	8.0	5.76
35	IV	8.0	7.71
36	IV	8.0	8.84
37	IV	8.0	8.47
38	IV	8.0	7.04
39	IV	8.0	5.25
40	IV	19.0	12.50
41	IV	8.0	5.56
42	IV	8.0	7.91
43	IV	8.0	6.89

 

전체 행 열과 그래프 순서에 따라 서브플롯 그리기

1) figure 객체를 생성한다.
fig=plt.figure()

2) 서브플롯을 그릴 axes 객체를 생성한다.
ax = fig.add_subplot(전체행개수,전체열개수,순서)

3) axes 객체에 그래프를 그린다.
ax.plot(x,y)

4) 축 공유하기 : 어떤 axes의 축을 공유할 것인지 지정한다.
sharex=axes객체, sharey=axes객체

# 1) figure 객체를 생성한다.
fig = plt.figure(figsize=(9,6), facecolor='ivory')

# 2) 서브플롯을 그릴 axes 객체를 생성한다.
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2, sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(2,2,3, sharex=ax1, sharey=ax1)
ax4 = fig.add_subplot(2,2,4)


# 3) axes 객체에 그래프를 그린다.
# 4) 축 공유하기 : 어떤 axes의 축을 공유할 것인지 지정한다.
ax1.plot(df1['x'],df1['y'],'o', label='ax1')
ax2.plot(df2['x'],df2['y'],'^', label='ax2')
ax3.plot(df3['x'],df3['y'],'*', label='ax3')
ax4.plot(df4['x'],df4['y'],'+', label='ax4')

# 4) 틱 변경하기
ax4.set_xticks(range(1,20,1))
ax4.set_yticks(range(1,15,1))

# 5) 범례 표시하기
ax1.legend(loc=2)
ax2.legend(loc=2)
ax3.legend(loc=2)
ax4.legend(loc=2)

# 6) figure 제목 추가하기
fig.suptitle('Anscombe', size=20)

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

plt.show()

 

이미지로 그래프 저장하기

  • fig.savefig(파일명, dpi=해상도)
  • 해상도 default : 100
fig.savefig('img100.png')
fig.savefig('img150.png', dpi=150)