본문 바로가기

Python_Intermediate/Matplotilb

Python Matplotlib -Subplots(한 화면에 여러개 그래프)

반응형

1. import module

import random
import matplotlib.pyplot as plt
from matplotlib import style


2. Sample Code

import random
import matplotlib.pyplot as plt
from matplotlib import style

style.use('fivethirtyeight')

fig = plt.figure()

def create_plots():
xs = []
ys = []

for i in range(10):
x = i
y = random.randrange(10)

xs.append(x)
ys.append(y)
return xs, ys

ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)

x, y = create_plots()
ax1.plot(x,y)

x, y = create_plots()
ax2.plot(x,y)

x, y = create_plots()
ax3.plot(x,y)

plt.savefig('3분위.png')
plt.close()


3. Sample Code 풀이

- Matplotlib에서 사용할 스타일 지정

style.use('fivethirtyeight')


- Sample 그래프에 사용할 데이터 지정(난수 사용)

def create_plots():
xs = []
ys = []

for i in range(10):
x = i
y = random.randrange(10)

xs.append(x)
ys.append(y)
return xs, ys


- SubPlot 위치 지정(fig.add_subplot(행 , 열 , 번호))

ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)


- X 축 / Y 축 데이터 지정

x, y = create_plots()
ax1.plot(x,y)

x, y = create_plots()
ax2.plot(x,y)

x, y = create_plots()
ax3.plot(x,y)


- 그래프 저장

plt.savefig('subplot.png')


- 그래프 종료

plt.close()


4. 출력물

반응형