본문 바로가기

Programing Language/Python

[plot]gridspec: subplots 업그레이드 버전

반응형

Introduction

Figure를 그릴 때, subplot만으로는 뭔가 아쉬울 때, 영역을 내마음대로 나누고 싶을 때, 그럴때 필요한게 바로 gridspec

Features

  • Figure를 그릴 때 영역을 내 자유자재로 나눌 수 있음

Usage

import matplotlib.gridspec as gridspec

# define gridspec
spec = gridspec.GridSpec(ncols=3, nrows=5, figure=fig)

# draw specific grid
ax = fig.add_subplot(spec[i//3,i%3])
ax = fig.add_subplot(spec[i:i+1,i:i+2])

Example code

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(15,20),tight_layout=True)

spec = gridspec.GridSpec(ncols=3, nrows=5, figure=fig)
axes = []
for i in range(len(df.columns)):
    ax = fig.add_subplot(spec[i//3,i%3])
    sct = ax.scatter(X_embedded[:,0],X_embedded[:,1], c=X[:,i], s= 10, alpha = .3)
#     ax.set_colorbar()
    fig.colorbar(sct, ax=ax)
    ax.set_title(df.columns[i])
    axes.append(ax)
plt.show() # bbox_inches='tight'
반응형