도표를 돋보이게 하는 격자선과 보조선에 대해 알아보겠습니다.
먼저 이번 편의 기본이 되는 코드를 보시겠습니다.
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
###--- Synthesizing data to be plotted ---###
x = np.arange(-4,4.1,0.5) # x range= -4. to 4.
ysin = np.sin(x) # Sine Function
###--- Plotting Start ---###
##-- Page Setup --##
fig = plt.figure() # Define "figure" instance
fig.set_size_inches(6,4.5) # Physical page size in inches, (lx,ly)
suptit="No Grid Lines"
fig.suptitle(suptit,fontsize=15) # Title for the page
##-- Plotting for axis1 --##
ax1 = fig.add_subplot(1,1,1) # subplot(# of rows, # of columns, indicater)
ax1.plot(x,ysin) # plotting line graph
ax1.xaxis.set_major_locator(MultipleLocator(1)) # For Major Ticks
ax1.xaxis.set_minor_locator(MultipleLocator(0.5)) # For minor Ticks
ax1.set_xlabel('X',fontsize=12)
ax1.set_ylim(-1.5,1.5)
ax1.set_ylabel('Y',fontsize=12)
ax1.tick_params(axis='both',which='major',labelsize=10)
##-- Seeing or Saving Pic --##
#plt.show() #- If want to see on screen -#
outdir = "./"
outfnm = outdir+"05_plot_accessary.grid0.png" # File format is decided by the file name, eg. png here
#fig.savefig(outfnm,dpi=100,facecolor='0.9',bbox_inches='tight') # dpi: pixels per inch
fig.savefig(outfnm,dpi=100,facecolor='0.9') # dpi: pixels per inch
sys.exit()
위 코드를 실행하면 밋밋한 도면에 사인 함수가 그려집니다.
격자선은 Ticks를 따라 수평/수직 선을 그어 도표에 격자를 그리는 기능입니다. 격자선을 그리는 명령어는
Axes.grid(b=None, which='major', axis='both', **kwargs) 입니다.
괄호 안이 비어있으면, 격자선이 있으면 없애고, 없으면 그립니다. (b=True or False, Toggle)
무언가 키워드가 하나라도 주어지면 그에 맞춰 격자선을 그립니다.
which= 'major', 'minor', 'both' : 주격자와 부격자를 따로 설정할 수 있습니다.
axis='x', 'y', 'both' : 어느 축으로 그릴 것인지 설정입니다.
위 예제 프로그램에 다음 두가지 경우를 추가할 경우 각각의 결과는 아래 그림과 같습니다.
ax1.grid()
ax1.grid(color='r',linestyle='-.',linewidth=2)
그림을 그리다 보면 필요에 따라 보조선을 그어 도표를 돋보이게 할 수 있습니다. 예를 들면 위 그림에 y=0에 해당하는 위치에 가로선을 그어주면 보기가 더 좋겠죠. 도표의 보조선을 그리는 방법은 크게 보아 3가지가 있습니다. 간단할 수록 자유도가 떨어지고, 자유도가 높을 수록 복잡해집니다. (당연하겠죠?)
Axes.axhline(y=0, xmin=0, xmax=1, **kwargs)
Axes.hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', *, data=None, **kwargs)
"h"를 "v"로 바꾸면 수직선입니다.
Axes.axhline()의 경우 y 값 하나만 주어지면 도표의 왼쪽 끝에서 오른쪽 끝까지 선을 그어줍니다. 간단하죠.
Axes.hlines()의 경우, y 값과 더불어 x 시작과 끝 값이 주어져야 합니다. 여기서 값들은 Data 데이타 기준입니다. (도표에 보이는 실제 x, y 값들을 의미합니다.)
위 예제 프로그램에 다음 2가지 경우를 추가한 각각의 결과는 아래 그림과 같습니다.
ax1.axhline(y=0.,color='k',linestyle=':')
ax1.vlines(x=0.,ymin=-1.,ymax=1.)
위 그림을 보시면 빨간 점선이 대각으로 그려져 있는 걸 볼 수 있습니다.
이렇게 자유로운 선을 그릴 경우, 그냥 Axes.plot()을 이용하시면 됩니다.
위 그림의 경우,
ax1.plot([0,4],[0,1.5],'r--')
가 추가된 것입니다.
주의할 점은, (x1,y1)에서 (x2,y2)로 선을 그릴 경우, 위 명령어에서는 [x1,x2], [y1,y2]의 형태로 들어간다는 점입니다. 또한, color='r', linestyle='--'을 'r--'로 축약할 수 있다는 점도 흥미롭습니다.
위 사인 함수 그래프에서 그냥 x축과 y축을 가운데에 그리면 좋지 않을까요?
그러기 위해선 도표의 축 Spines를 뜯어 고쳐야 합니다.
제일 위의 예제 프로그램에서 다음과 같은 명령어를 추가하면 위 그림과 같이 변합니다.
ax1.spines['left'].set_position('center') # Move left-side Y axis to center
ax1.spines['bottom'].set_position('center') # Move bottom X axis to center
ax1.spines['right'].set_visible(False) # Remove right-side Y axis
ax1.spines['top'].set_visible(False) # Remove top X axis
ax1.xaxis.set_ticks_position('bottom') # Default is 'both'
ax1.yaxis.set_ticks_position('left') # Default is 'both'
이상 격자선과 보조선에 대해 알아보았습니다.
"""
제 개인적 목표는
이 목표에 닿기 위해 일단 제가 나름 좀 아는 Python, 그 중에서도 Numpy와 Matplotlib로부터 시작하려 합니다.
"""
[Matplotlib] 00. Intro + 01. Page Setup
[Matplotlib] 02. Axes Setup: Subplots
[Matplotlib] 03. Axes Setup: Text, Label, and Annotation
[Matplotlib] 04. Axes Setup: Ticks and Tick Labels
[Matplotlib] 05. Plot Accessories: Grid and Supporting Lines