matplotlib를 이용해서 데이터 시각화하기
matplotlib를 이용해서 데이터 시각화하기¶
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
Matplotlib¶
Matplotlib은 Python에서 데이터를 시각화하기 위한 라이브러리입니다. 그래프와 차트를 쉽게 생성할 수 있도록 다양한 도구와 기능을 제공합니다.
Matplotlib 기본¶
matplotlib는 주로 plt
로 축약하여 사용합니다. 가장 기본인 그래프 유형은 선 그래프로 plot()
함수를 이용해서 표현합니다.
plt.plot([1, 2, 3, 4, 5, 4, 3, 2, 1])
[<matplotlib.lines.Line2D at 0x124fc6c30>]
다양한 옵션들¶
matplotlib에서는 그래프를 꾸밀 수 있는 다양한 옵션을 제공합니다. 하나씩 살펴보겠습니다.
figure()
: 그래프를 그릴 일종의 도화지입니다.facecolor
(배경색),figsize
(크기) 등을 설정할 수 있습니다.title()
: 그래프의 제목을 설정합니다.xlabel()
,ylabel()
: x축과 y축의 이름을 설정합니다.grid()
: 그래프에 격자선을 추가합니다.legend()
: 범례를 설정합니다. 범례의 이름은plot()
안에labels
로 전달해 주어야 합니다.
plot에도 여러 가지 옵션을 추가해서 다양하게 표현할 수 있습니다.
label
: 차트의 label을 설정합니다.marker
: 각 꼭짓점의 모양을 설정합니다.markersize
: marker의 사이즈를 설정합니다.color
: plot의 색상을 설정합니다.linestyle
: 선의 스타일을 설정합니다.
x = np.arange(0, 10)
y = np.sin(x)
y2 = np.cos(x)
# 도화지
plt.figure(facecolor='pink', figsize=(16, 10))
# plot: 선 그래프
plt.plot(x, y, label='sin', marker='o', markersize=8, color='red')
plt.plot(x, y2, label='cos', marker='x')
plt.title('Sin Graph') # chart 제목
plt.xlabel('Time') # x축 이름
plt.ylabel('Aplitude') # y축 이름
plt.grid() # 그리드 추가
plt.legend(loc=(1.01, 0)) # 범례
<matplotlib.legend.Legend at 0x12633a0f0>
여러 개의 그래프 그리기¶
위의 그래프는 두 개의 선 그래프를 하나의 도화지 안에 나타낸 것입니다. 그렇다면 두 그래프를 따로 그릴 수는 없을까요? 두 그래프를 따로 그리고 싶다면 subplots()
를 사용합니다.
nrows
와 ncols
를 사용해서 각 행과 열에 몇 개의 그래프를 그릴 건지 설정합니다. 아래의 예시는 1행 2열, 총 2개의 그래프를 subplots()
를 이용해 그린 것입니다.
x = np.arange(1, 20, 2)
y = x * 2
# subplots() : 그래프 여러 개를 동시에 그릴 때 사용
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))
ax1.plot(x, y, color='red', marker='o', linestyle='--', label='line')
ax2.bar(x, y, color='pink', label='bar')
ax1.legend()
ax2.legend()
<matplotlib.legend.Legend at 0x15b00f6e0>
산점도¶
matplotlib의 scatter()
함수를 이용해서 산점도를 표현할 수 있습니다. 산점도 역시 marker
인자로 점의 스타일을 설정할 수 있습니다.
x1 = np.random.rand(100) -1
x2 = np.random.rand(100)
y1 = np.random.rand(100)
y2 = np.random.rand(100)
plt.scatter(x1, y1, marker='x')
plt.scatter(x2, y2, marker='o')
<matplotlib.collections.PathCollection at 0x15ae5ddf0>
df = pd.read_csv('./data.csv')
df
x | y | Label | |
---|---|---|---|
0 | 5.539907 | 2.780370 | Medium |
1 | 5.309798 | 3.342864 | Large |
2 | 4.367271 | 4.551839 | Large |
3 | 3.812863 | 2.447711 | Large |
4 | 5.213783 | 5.133856 | Large |
... | ... | ... | ... |
95 | -10.973173 | -6.348612 | Small |
96 | -12.787083 | -5.901621 | Small |
97 | -12.365544 | -7.557758 | Small |
98 | -12.201273 | -9.228887 | Small |
99 | -13.375726 | -8.303337 | Small |
100 rows × 3 columns
df_large = df[df['Label'] == 'Large']
df_medium = df[df['Label'] == 'Medium']
df_small = df[df['Label'] == 'Small']
plt.scatter(df_large['x'], df_large['y'], label='large')
plt.scatter(df_medium['x'], df_medium['y'], label='medium')
plt.scatter(df_small['x'], df_small['y'], label='small')
plt.legend()
<matplotlib.legend.Legend at 0x15dd80140>
pandas만 가지고 산점도 그리기¶
matplotlib를 사용하지 않고 pandas 만으로 산점도를 그릴 수도 있습니다.
# 판다스만으로 그래프 그리기
ax = df_large.plot(x='x', y='y', kind='scatter', c='b', label='Large')
df_medium.plot(x='x', y='y', kind='scatter', c='orange', label='Medium', ax=ax)
df_small.plot(x='x', y='y', kind='scatter', c='g', label='Small', ax=ax)
<Axes: xlabel='x', ylabel='y'>
boxplot¶
상자수염 그림이라고도 불리는 boxplot을 그려보겠습니다. boxplot은 분석하고자 하는 데이터의 범위를 측정하고 이상치 값을 확인하고 처리하기 위해 사용하는 그래프입니다. boxplot은 boxplot()
함수를 사용합니다.
s1 = np.random.normal(loc=5, scale=0.5, size=1000)
plt.boxplot(s1)
{'whiskers': [<matplotlib.lines.Line2D at 0x15ebbb0e0>, <matplotlib.lines.Line2D at 0x15ebbb260>], 'caps': [<matplotlib.lines.Line2D at 0x15ebb9ac0>, <matplotlib.lines.Line2D at 0x15ebbb7a0>], 'boxes': [<matplotlib.lines.Line2D at 0x15ebbad20>], 'medians': [<matplotlib.lines.Line2D at 0x15ebbba70>], 'fliers': [<matplotlib.lines.Line2D at 0x15ebbbda0>], 'means': []}
막대그래프¶
가장 기본이라고 할 수 있는 막대그래프(barplot)입니다. matplotlib의 bar()
함수를 사용합니다. x
는 x축, height
는 각 데이터의 값을 의미합니다.
label = ['kor', 'usa', 'china']
value = [100, 130, 150]
color = ['r', 'g', 'b']
plt.bar(x=label, height=value, color=color, alpha=0.5)
<BarContainer object of 3 artists>
위의 표를 더 드라마틱하게 표현하려면 어떻게 해야 할까요? ylim()
을 사용해서 y축의 범위를 조절해주면 됩니다.
label = ['kor', 'usa', 'china']
value = [100, 130, 150]
color = ['r', 'g', 'b']
plt.ylim(90, 160) # y축 범위 지정
plt.bar(x=label, height=value, color=color, alpha=0.5)
<BarContainer object of 3 artists>