Computer Science/Python

[Python] matplotlib 기초 및 예제

2021. 2. 9. 13:08

matplotlib는 Python의 데이터 시각화 패키지로, 이를 활용하면 손쉽게 데이터를 그래프로 표현할 수 있다.

 

이 포스트에서는 다양한 그래프 및 기능을 예제로 보여주려고 한다.

 

 

Importing

import matplotlib.pyplot as plt # matplotlib importing

import seaborn as sns # matplotlib를 기반으로 한 패키지로, 더 화려한 그래프를 그릴 수 있음.

파이썬 환경에 matplotlib 패키지가 없다면 pip으로 설치해줄 수 있다 (pip install matplotlib)

 

Jupyter에서 matplotlib와 관련된 magic function은 다음과 같다.

%matplotlib inline # inline에 그래프 생성

%matplotlib qt # 새 창에 그래프 생성

 

그래프 종류

1. Line graph (선 그래프)

plt.plot(x, y)

 

2. Scatter plot (산점도)

# 1.
plt.plot(x, y, 'o')

# 2.
plt.scatter(x, y)

# 3.
plt.scatter(x=xData,
            y=yData,
            s=Sdata,   # 크기 조절
            c=cData,   # 색상 조절
            alpha=0.5) # 투명도 조절

# 4.
df.plot.scatter(x='Column1', y='Column2')

# 5.
df.plot.hexbin(x='Column1', y='Column2', gridSize=5) # 육각 그래프

# 6.
sns.regplot(x='Column1', y='Column2', data=df) # 회귀선 포함

# 7.
sns.lmplot(x='Column1', y='Column2', data=df,
           hue='Column3',                 # 색상 조절
           markers['o','x'],              # 모양 조절
           scatter_kew={'s': df['Size']}) # 크기 조절

 

3. Bar plot (막대 그래프)

sns.barplot(x='Column1', y='Column2', data=df)

 

4. Histogram (히스토그램, 일변량 그래프)

# 1.
plt.hist(values, bins=10) # 10개의 구간으로 나눈 histogram

# 2.
ax = plt.subplots()
ax = series.plot.hist()

# 3.
sns.distplot(values) # kde(밀집도), hist(히스토그램), rug(양탄자)를 True, False로 설정 가능.

 

5. Box plot (상자 그림)

# 1.
plt.boxplot([values1,values2],
			labels=['Value1','Value2'])
            
# 2.
fig, ax = plt.subplots()
ax = df.plot.box(ax=ax)

# 3.
sns.boxplot(x='Column1', y='Column2', data=df)

 

6. Jointplot (산점도 그래프 + 히스토그램)

# 1.
sns.jointplot(x='Column1', y='Column2', data=df)

# 2.
sns.jointplot(x='Column1', y='Column2', data=df, kind="hex") # 점이 겹쳐있을 때 이를 쉽게 구분하기 위해 육각 그래프를 이용

 

7-1. 밀집도

series.plot.kde()

 

7-2. 이차원 밀집도

sns.kdeplot(data=df['Column1'], data2=df['Column2'], shdate=True) # 음영 효과 포함

 

 

8. Count 그래프

sns.countplot('Column1', data=df)

 

 

9. 바이올린 그래프

sns.violinplot(x='Column1', y='Column2', data=df)

 

 

10. 관계 그래프

# 1.
sns.pairplot(df)

# 2.
pairGrid = sns.PairGrid(df)
pairGrid = pairGrid.map_upper(sns.regplot) # 대각선 위 산점도 그래프
pairGrid = pairGrid.map_lower(sns.kdeplot) # 대각선 이차원 밀집도
pairGrid = pairGrid.map_diag(sns.distplot, rug=True) # 대각선 히스토그램
plt.show()

 

 

 

기능

1. 그래프 꾸미기

plt.set_title("") # 제목 설정
plt.set_xlabel("") # x축 라벨 설정
plt.set_ylabel("") # y축 라벨 설정

# 혹은 아래도 가능
plot = plt.plot(~) # plot 생성
plot.set_title("") # 제목 설정
plot.set_xlabel("") # x축 라벨 설정
plot.set_ylabel("") # y축 라벨 설정


# Legend 생성
plt.plot(x, y1, label="Value1")
plt.plot(x, y2, label="Value2")
plt.legend()


# seaborn 패키지 스타일
sns.set_style('darkgrid') # whitegrid, dark, white, ticks

 

2. 여러 개의 그래프 그리기

# 1.
fig = plt.figure()
plot1 = fig.add_subplot(2,2,1)
plot2 = fig.add_subplot(2,2,2)
plot3 = fig.add_subplot(2,2,3)
plot4 = fig.add_subplot(2,2,4)

plot1.plot(~)
plot2.plot(~)
plot3.plot(~)
plot4.plot(~)

plot.set_title("-") # plot 제목 설정

fig.suptitle("-") # 전체 제목 설정

fig.tight_layout() # 그래프 레이아웃 조절

fig

# 2.
plot = sns.lmplot(x='Column1', y='Column2', data=df,
                  col='Column3', # 나누는 기준 열 지정
                  col_wrap=2)    # 최대 열 갯수 지정
                  
# 3.          
facetGrid = sns.FacetGrid(df, col='Column3') # 나누는 기준 열 지정 (row도 추가로 지정 가능)
facetGrid.map(sns.scatter, 'Column1', 'Column2')
facetGrid.add_legend()

 

3. 그래프 저장

plt.savefig('FILE PATH') # 파일 저장, 이때 plt.show()가 먼저 나와서는 안 된다.   

 

4. 축 범위 설정

plt.xlim([5, 10])          # X축의 범위
plt.ylim([50, 100])        # Y축의 범위
plt.axis([5, 10, 50, 100]) # X, Y축의 범위

 

 

참고

  • matpotlib documentation과 seaborn documentation을 참고하면 더 많은 정보를 확인할 수 있다.

 

 

 

Reference

  • 최은석. "데이터 시각화." 데이터 분석을 위한 파이썬 철저 입문. 위키북스, 2018. 283-329.
  • Do it! 데이터분석을 위한 판다스 입문
  • codetorial.net/matplotlib/axis_range.html

 

 

728x90
반응형