파이썬/시각화 matplot

[matplot] 위치, 크기 지정하여 플롯 그리기

Merware 2023. 5. 15. 16:19

[학습목표]
그래프의 위치, 크기를 지정하여 그래프를 그릴 수 있다.

 

라이브러리 임포트

import matplotlib.pyplot as plt

 

위치, 크기 지정하여 그래프 그리기

figure, axes

  • figure : 그림이 그려지는 캔버스
  • axes : 하나의 그래프

위치, 크기 지정하여 그래프 그리기

1) figure 객체를 생성한다.
fig = plt.figure(figsize=(가로길이,세로길이))

2) figure객체의 add_axes 메소드로 위치와 크기를 지정하여 axes 객체를 생성한다.
ax1 = fig.add_axes([left, bottom, width, height])
left, bottom : 상대적인 시작 위치 (figsize의 크기를 1이라고 했을 때 상대적 위치)
width, height : 상대적인 크기(figsize의 크기를 1이라고 했을 때 상대적 크기)

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

4) axes에 제목 추가.
ax1.set_title(제목)

위치와 크기를 자유롭게 지정하여 axes 객체 만들기

  • add_axes를 사용하면, 서브플롯의 크기와 위치를 자유롭게 지정할 수 있다.
  • 그래프를 겹쳐그리거나, 크기가 각각 다른 그래프를 그릴 수 있다.

앤스콤 4분할 그래프 그리기

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']

print('==== df1.head(2) ====\n'  , df1.head(2))
print('\n==== df2.head(2) ====\n', df2.head(2))
print('\n==== df3.head(2) ====\n', df3.head(2))
print('\n==== df4.head(2) ====\n', df4.head(2))

"""
==== df1.head(2) ====
   dataset     x     y
0       I  10.0  8.04
1       I   8.0  6.95

==== df2.head(2) ====
    dataset     x     y
11      II  10.0  9.14
12      II   8.0  8.14

==== df3.head(2) ====
    dataset     x     y
22     III  10.0  7.46
23     III   8.0  6.77

==== df4.head(2) ====
    dataset    x     y
33      IV  8.0  6.58
34      IV  8.0  5.76
# 1)figure 객체를 생성한다.
fig = plt.figure(figsize=(8,6))

# 2) figure객체의 add_axes 메소드로 위치와 크기를 지정하여 axes 객체를 생성한다.
ax1 = fig.add_axes([0,0.5,0.4,0.4])
ax2 = fig.add_axes([0.5,0.5,0.4,0.4])
ax3 = fig.add_axes([0,0,0.4,0.4])
ax4 = fig.add_axes([0.5,0,0.4,0.4])

# 3) axes에 그래프를 그린다.
ax1.plot(df1['x'],df1['y'],'o')
ax2.plot(df2['x'],df2['y'],'r^')
ax3.plot(df3['x'],df3['y'],'k*')
ax4.plot(df4['x'],df4['y'],'m+')

# 4) axes에 제목 추가.
ax1.set_title('ax1')
ax2.set_title('ax2')
ax3.set_title('ax3')
ax4.set_title('ax4')
Text(0.5, 1.0, 'ax4')