본문 바로가기

코딩/파이썬과 데이터 사이언스

파이썬과 데이터 사이언스 : matplotlib 라이브러리

 

matplotlib.pyplot 모듈이 제공하는 여러 그래프 타입의 예

  • matplotlib.pyplot.plot()
  • matplotlib.pyplot.bar()
  • matplotlib.pyplot.barh()
  • matplotlib.pyplot.scatter()
  • matplotlib.pyplot.step()
  • matplotlib.pyplot.boxplot()

matplotlib.pyplot 모듈이 제공하는 여러 함수의 예 (matplotlib.pyplot as plt)

 

plt.axhline() X축 수평으로 라인을 표시
plt.axvline() Y축 수직으로 라인을 표시
plt.grid(boolean) 그래프에 그리드를 표시할지 설정
plt.save() 그래프를 파일로 저장
plt.show() 화면에 그래프를 출력
plt.title() 그래프의 타이틀을 설정
plt.xlabel() X축 라벨을 설정
plt.xlim([a, b]) X축의 하한(a)/상한(b) 값을 설정
plt.xticks() X축의 눈금 라벨 개수를 설정
plt.ylabel() Y축 라벨을 설정
plt.ylim([a, b]) X축의 하한(a)/상한(b) 값을 설정
plt.yticks() Y축의 눈금 라벨 개수를 설정

 

아래의 코드를 통해 화면에 빈 그래프(플롯)을 출력합니다.

 

import matplotlib.pyplot as plt

plt.title('plot 1')

plt.show()

 

 

다수 개의 그래프를 출력할 때 subplots()이 사용될 수 있습니다.

 

import matplotlib.pyplot as plt

fig, axs = plt.subplots(nrows=2, ncols=2)

axs[0][0].set(title='plot 0,0')
axs[0][1].set(title='plot 0,1')
axs[1][0].set(title='plot 1,0')
axs[1][1].set(title='plot 1,1')

plt.show()

# --------------------------------------------------

# fig = plt.figure()

# axs1 = fig.add_subplot(2, 2, 1)
# axs2 = fig.add_subplot(2, 2, 2)
# axs3 = fig.add_subplot(2, 2, 3)
# axs4 = fig.add_subplot(2, 2, 4)

# fig.suptitle('plot main')

# axs1.set_title('plot 1')
# axs1.set_xlabel('X label')
# axs1.set_ylabel('Y label')
# axs2.set_title('plot 2')
# axs3.set_title('plot 3')
# axs4.set_title('plot 4')

# fig.tight_layout()

# plt.show()

 

matplotlib.pyplot.plot()

plot() 메서드를 이용해 선 그래프를 그릴 수 있습니다.

 

 

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

# --------------------------------------------------

# import matplotlib.pyplot as plt

# fig, ax = plt.subplots()
# ax.plot([1, 2, 3, 4], [1, 4, 9, 16])
# plt.show()

# --------------------------------------------------

# import matplotlib.pyplot as plt
# import numpy as np

# fig, ax = plt.subplots()
# ax.plot([1, 2, 3, 4], [1, 4, 9, 16])
# ax.set(xlim=(0, 5), xticks=np.arange(0, 5), ylim=(0, 17), yticks=np.arange(0, 17, 2))

# plt.show()

 

아래는 화면에 출력되는 그래프(figure) 각 영영 정보입니다.

 

출처 : matplotlib.org

 

plot()으로 선이 이어지지 않은 그래프를 그리는 것도 가능합니다.

 

 

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
data = {
    'a': np.arange(50),
    'c': np.random.randint(0, 50, 50),
    'd': np.random.randn(50)
}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.plot(data['a'], data['b'], color='red', marker='o', linestyle='none')
plt.title('matplotlib.pyplot.plot()')
plt.xlabel('x label')
plt.ylabel('y label')
plt.grid()

plt.show()

 

plt.style.use('ggplot') 코드 추가를 통해 matplotlib에서 제공하는 여러 스타일을 사용할 수 있습니다.

 

 

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
data = {
    'a': np.arange(50),
    'c': np.random.randint(0, 50, 50),
    'd': np.random.randn(50)
}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.style.use('ggplot')
plt.plot(data['a'], data['b'], marker='o', linestyle='none')
plt.title('matplotlib.pyplot.plot()')
plt.xlabel('x label')
plt.ylabel('y label')

plt.show()

matplotlib.pyplot.bar() / barh()

bar() 메서드를 이용해 막대 그래프를 그릴 수 있습니다.

 

 

 

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
x = np.arange(8) + 0.5
y = np.random.uniform(2, 7, len(x))

plt.bar(x, y)
plt.grid()  # 참고 : plt.grid(visible=True, axis='y')

plt.show()

# --------------------------------------------------

# import matplotlib.pyplot as plt
# import numpy as np

# np.random.seed(1)
# x = np.arange(8) + 0.5
# y = np.random.uniform(2, 7, len(x))

# fig, ax = plt.subplots()
# ax.bar(x, y, width=1, color='g', edgecolor="white", linewidth=0.7)
# ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8))
# plt.grid()

# plt.show()

 

아래는 동일한 데이터에 대하여 barh() 메서드를 사용해 막대 그래프를 그리는 코드입니다.

 

 

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
x = np.arange(8) + 0.5
y = np.random.uniform(2, 7, len(x))

plt.barh(x, y)
plt.grid()

plt.show()

matplotlib.pyplot.scatter()

scatter() 메서드를 이용해 산포도 그래프를 그릴 수 있습니다.

 

 

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(3)
x = 4 + np.random.normal(0, 2, 24)
y = 4 + np.random.normal(0, 2, len(x))
sizes = np.random.uniform(15, 80, len(x))
colors = np.random.uniform(15, 80, len(x))

plt.scatter(x, y, s=sizes, c=colors, vmin=0, vmax=100)

plt.show()

# --------------------------------------------------

# import matplotlib.pyplot as plt
# import numpy as np

# np.random.seed(3)
# x = 4 + np.random.normal(0, 2, 24)
# y = 4 + np.random.normal(0, 2, len(x))
# sizes = np.random.uniform(15, 80, len(x))
# colors = np.random.uniform(15, 80, len(x))
 
# fig, ax = plt.subplots()
# ax.scatter(x, y, s=sizes, c=colors, vmin=0, vmax=100)
# ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8))
 
# plt.show()

matplotlib.pyplot.step()

step() 메서드를 이용해 스텝 그래프를 그릴 수 있습니다.

 

 

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(3)
x = np.arange(8) + 0.5
y = np.random.uniform(2, 7, len(x))

plt.step(x, y)

plt.show()


# --------------------------------------------------

# import matplotlib.pyplot as plt
# import numpy as np

# np.random.seed(3)
# x = np.arange(8) + 0.5
# y = np.random.uniform(2, 7, len(x))

# fig, ax = plt.subplots()
# ax.step(x, y, linewidth=2.5)
# ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8))

# plt.show()

matplotlib.pyplot.hist()

hist() 메서드를 이용해 히스토그램 그래프를 그릴 수 있습니다.

 

 

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
x = 4 + np.random.normal(0, 1.5, 200)

plt.hist(x)

plt.show()


# --------------------------------------------------

# import matplotlib.pyplot as plt
# import numpy as np
#
# np.random.seed(1)
# x = 4 + np.random.normal(0, 1.5, 200)
#
# fig, ax = plt.subplots()
# ax.hist(x, bins=8, linewidth=0.5, edgecolor="white")
# ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 56), yticks=np.linspace(0, 56, 9))
#
# plt.show()

matplotlib.pyplot.boxplot()

아래는 boxplot() 메서드를 사용해 그래프를 그리는 코드입니다.

 

 

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(10)
D = np.random.normal((3, 5, 4), (1.25, 1.00, 1.25), (100, 3))

plt.boxplot(D)

plt.show()


# --------------------------------------------------

# import matplotlib.pyplot as plt
# import numpy as np
#
# np.random.seed(10)
# D = np.random.normal((3, 5, 4), (1.25, 1.00, 1.25), (100, 3))
#
# plt.style.use('_mpl-gallery')
#
# fig, ax = plt.subplots()
# VP = ax.boxplot(D, positions=[2, 4, 6], widths=1.5, patch_artist=True,
#                 showmeans=False, showfliers=False,
#                 medianprops={"color": "white", "linewidth": 0.5},
#                 boxprops={"facecolor": "C0", "edgecolor": "white", "linewidth": 0.5},
#                 whiskerprops={"color": "C0", "linewidth": 1.5},
#                 capprops={"color": "C0", "linewidth": 1.5})
#
# ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8))
#
# plt.show()

부록 1. matplotlib으로 연도 별 소비자물가지수 정보 그리기

그래프로 그리는 데이터는 한국은행에서 제공하는 소비자물가지수 정보입니다.

소비자물가지수_02223652.csv
0.00MB

 

 

import matplotlib.pyplot as plt
import pandas as pd

plt.rc('font', family='Malgun Gothic')
# plt.rcParams['font.family'] = 'Malgun Gothic'

cpi = pd.read_csv('소비자물가지수_02223652.csv', index_col='계정항목')
cpi.index = [i.strip() for i in cpi.index]
cpi = cpi.drop(columns=['통계표', '단위', '가중치', '변환'])
cpi = cpi.T

plt.figure(figsize=[16, 9])
plt.plot(cpi['총지수'], color='blue', linestyle='solid', marker='o')
plt.grid(True)
plt.title('소비자물가지수')
plt.xlabel('총지수')
plt.ylabel('연도')
plt.xticks(rotation=90)
plt.show()

 

아래는 matplotlib의 plot()이 아닌 DataFrame의 plot() 메서드로 그래프를 그리는 코드입니다.

 

 

import matplotlib.pyplot as plt
import pandas as pd

plt.rc('font', family='Malgun Gothic')

cpi = pd.read_csv('소비자물가지수_02223652.csv', index_col='계정항목')
cpi.index = [i.strip() for i in cpi.index]
cpi = cpi.drop(columns=['통계표', '단위', '가중치', '변환'])
cpi = cpi.T
cpi_parts = cpi.tail(10)

cpi_parts.plot(title='소비자물가지수', figsize=(16, 9), legend=True, marker='o', rot=90)
plt.grid()
plt.xlabel('총지수')
plt.ylabel('연도')
plt.show()

부록 2. matplotlib로 연도 별 소비자물가지수와 기준금리 비교하기

아래는 2중의 Y축을 갖는 그래프를 그리는 코드입니다.

그래프로 그리는  데이터는 한국은행에서 제공하는 소비자물가지수와 기준금리 정보입니다.

한국은행 기준금리 및 여수신금리_03001843.csv
0.00MB

 

 

import matplotlib.pyplot as plt
import pandas as pd

plt.rc('font', family='Malgun Gothic')

cpi = pd.read_csv('소비자물가지수_02223652.csv', index_col='계정항목')
cpi.index = [i.strip() for i in cpi.index]
cpi = cpi.drop(columns=['통계표', '단위', '가중치', '변환'])
cpi = cpi.T
cpi_parts = cpi.tail(10)['총지수']

gdp = pd.read_csv('한국은행 기준금리 및 여수신금리_03001843.csv', index_col='계정항목')
gdp.index = [i.strip() for i in gdp.index]
gdp = gdp.drop(columns=['통계표', '단위', '변환'])
gdp = gdp.T
gdp_parts = gdp.tail(10)['한국은행 기준금리']

fig, ax1 = plt.subplots()
ax1.set_title('소비자물가지수와 기준금리')
color = 'tab:red'
ax1.set_ylabel('총지수', color=color)
ax1.plot(cpi_parts, color=color, marker='o')
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('기준금리', color=color)
ax2.plot(gdp_parts, color=color, marker='o')
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()

plt.show()