🔥알림🔥
① 테디노트 유튜브 - 구경하러 가기!
② LangChain 한국어 튜토리얼 바로가기 👀
③ 랭체인 노트 무료 전자책(wikidocs) 바로가기 🙌

6 분 소요

데이터 시각화를 위한 라이브러리인 matplotlib 의 주요 그래프와 세부 옵션들에 대하여 알아보는 튜토리얼입니다.

matplotlib 을 활용한 다양한 그래프 그리기

In [1]:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
In [2]:
plt.rc('font', family='NanumBarunGothic') 
plt.rcParams["figure.figsize"] = (12, 9)

1. Scatterplot

0 ~ 1 사이의 임의의 랜덤한 값을 생성합니다.

In [3]:
np.random.rand(50)
Out[3]:
array([0.13994235, 0.54483825, 0.13611607, 0.14252471, 0.85405767,
       0.23978414, 0.41539415, 0.72585139, 0.05476896, 0.09767999,
       0.57250905, 0.34236077, 0.05739072, 0.09037755, 0.2407536 ,
       0.69483586, 0.58374007, 0.35198442, 0.23934772, 0.3552033 ,
       0.54057305, 0.98497802, 0.68780011, 0.49925425, 0.45866565,
       0.39529508, 0.76735131, 0.40984807, 0.44292816, 0.13558484,
       0.47268804, 0.37721442, 0.41900356, 0.98923134, 0.15272075,
       0.93012092, 0.51567587, 0.47109335, 0.58929041, 0.74267018,
       0.08056103, 0.51134175, 0.13922716, 0.6658347 , 0.93363798,
       0.96365923, 0.0585498 , 0.42276105, 0.02541926, 0.88301974])

0 부터 50개의 값을 순차적으로 생성합니다.

In [4]:
np.arange(50)
Out[4]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49])

1-1. x, y, colors, area 설정하기

  • colors 는 임의 값을 color 값으로 변환합니다.
  • area는 점의 넓이를 나타냅니다. 값이 커지면 당연히 넓이도 커집니다.
In [5]:
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.arange(50)
area = x * y * 1000
In [6]:
plt.scatter(x, y, s=area, c=colors)
plt.show()

1-2. cmap과 alpha

  • cmap에 컬러를 지정하면, 컬러 값을 모두 같게 가져갈 수도 있습니다.
  • alpha값은 투명도를 나타내며 0 ~ 1 사이의 값을 지정해 줄 수 있으며, 0에 가까울 수록 투명한 값을 가집니다.
In [7]:
np.random.rand(50)
Out[7]:
array([0.69112835, 0.90466578, 0.17170103, 0.54585369, 0.21890011,
       0.30739773, 0.30991678, 0.56353779, 0.22915579, 0.45009353,
       0.63251002, 0.00353594, 0.71615913, 0.07014487, 0.84075335,
       0.84894898, 0.09471014, 0.62284626, 0.98501247, 0.2359996 ,
       0.62802025, 0.73391038, 0.55165717, 0.70159667, 0.84260943,
       0.97411019, 0.33447662, 0.09478174, 0.20860898, 0.55922318,
       0.35915282, 0.80718566, 0.96622479, 0.69894493, 0.88807869,
       0.91508098, 0.20216999, 0.29292694, 0.69267264, 0.98240378,
       0.81761813, 0.2285661 , 0.14199793, 0.49541932, 0.91811726,
       0.34500529, 0.07522612, 0.0460507 , 0.73956345, 0.21739672])
In [8]:
plt.figure(figsize=(12, 6))

plt.subplot(131)
plt.scatter(x, y, s=area, cmap='blue', alpha=0.1)
plt.title('alpha=0.1')
plt.subplot(132)
plt.title('alpha=0.5')
plt.scatter(x, y, s=area, cmap='blue', alpha=0.5)
plt.subplot(133)
plt.title('alpha=1.0')
plt.scatter(x, y, s=area, cmap='blue', alpha=1.0)

plt.show()

2. Barplot, Barhplot

1개의 canvas 안에 다중 그래프 그리기

2-1. 기본 Barplot 그리기

In [9]:
x = ['Math', 'Programming', 'Data Science', 'Art', 'English', 'Physics']
y = [66, 80, 60, 50, 80, 10]

plt.bar(x, y, align='center', alpha=0.7, color='red')
plt.xticks(x)
plt.ylabel('Number of Students')
plt.title('Subjects')

plt.show()

2-2. 기본 Barhplot 그리기

barh 함수에서는 xticks로 설정했던 부분을 yticks로 변경합니다.

In [10]:
x = ['Math', 'Programming', 'Data Science', 'Art', 'English', 'Physics']
y = [66, 80, 60, 50, 80, 10]

plt.barh(x, y, align='center', alpha=0.7, color='green')
plt.yticks(x)
plt.xlabel('Number of Students')
plt.title('Subjects')

plt.show()

Batplot에서 비교 그래프 그리기

In [11]:
x_label = ['Math', 'Programming', 'Data Science', 'Art', 'English', 'Physics']
x = np.arange(len(x_label))
y_1 = [66, 80, 60, 50, 80, 10]
y_2 = [55, 90, 40, 60, 70, 20]

# 넓이 지정
width = 0.35

# subplots 생성
fig, axes = plt.subplots()

# 넓이 설정
axes.bar(x - width/2, y_1, width, align='center', alpha=0.5)
axes.bar(x + width/2, y_2, width, align='center', alpha=0.8)

# xtick 설정
plt.xticks(x)
axes.set_xticklabels(x_label)
plt.ylabel('Number of Students')
plt.title('Subjects')

plt.legend(['john', 'peter'])

plt.show()
In [12]:
x_label = ['Math', 'Programming', 'Data Science', 'Art', 'English', 'Physics']
x = np.arange(len(x_label))
y_1 = [66, 80, 60, 50, 80, 10]
y_2 = [55, 90, 40, 60, 70, 20]

# 넓이 지정
width = 0.35

# subplots 생성
fig, axes = plt.subplots()

# 넓이 설정
axes.barh(x - width/2, y_1, width, align='center', alpha=0.5, color='green')
axes.barh(x + width/2, y_2, width, align='center', alpha=0.8, color='red')

# xtick 설정
plt.yticks(x)
axes.set_yticklabels(x_label)
plt.xlabel('Number of Students')
plt.title('Subjects')

plt.legend(['john', 'peter'])

plt.show()

3. Line Plot

3-1. 기본 lineplot 그리기

In [13]:
x = np.arange(0, 10, 0.1)
y = 1 + np.sin(x)

plt.plot(x, y)

plt.xlabel('x value', fontsize=15)
plt.ylabel('y value', fontsize=15)
plt.title('sin graph', fontsize=18)

plt.grid()

plt.show()

3-2. 2개 이상의 그래프 그리기

  • color: 컬러 옵션
  • alpha: 투명도 옵션
In [14]:
x = np.arange(0, 10, 0.1)
y_1 = 1 + np.sin(x)
y_2 = 1 + np.cos(x)

plt.plot(x, y_1, label='1+sin', color='blue', alpha=0.3)
plt.plot(x, y_2, label='1+cos', color='red', alpha=0.7)

plt.xlabel('x value', fontsize=15)
plt.ylabel('y value', fontsize=15)
plt.title('sin and cos graph', fontsize=18)

plt.grid()
plt.legend()

plt.show()

3-3. 마커 스타일링

  • marker: 마커 옵션
In [15]:
x = np.arange(0, 10, 0.1)
y_1 = 1 + np.sin(x)
y_2 = 1 + np.cos(x)

plt.plot(x, y_1, label='1+sin', color='blue', alpha=0.3, marker='o')
plt.plot(x, y_2, label='1+cos', color='red', alpha=0.7, marker='+')

plt.xlabel('x value', fontsize=15)
plt.ylabel('y value', fontsize=15)
plt.title('sin and cos graph', fontsize=18)

plt.grid()
plt.legend()

plt.show()

3-4 라인 스타일 변경하기

  • linestyle: 라인 스타일 변경 옵션
In [16]:
x = np.arange(0, 10, 0.1)
y_1 = 1 + np.sin(x)
y_2 = 1 + np.cos(x)

plt.plot(x, y_1, label='1+sin', color='blue', linestyle=':')
plt.plot(x, y_2, label='1+cos', color='red', linestyle='-.')

plt.xlabel('x value', fontsize=15)
plt.ylabel('y value', fontsize=15)
plt.title('sin and cos graph', fontsize=18)

plt.grid()
plt.legend()

plt.show()

4. Areaplot (Filled Area)

matplotlib에서 area plot을 그리고자 할 때는 fill_between 함수를 사용합니다.

In [17]:
y = np.random.randint(low=5, high=10, size=20)
y
Out[17]:
array([5, 7, 7, 6, 5, 9, 8, 5, 6, 7, 7, 7, 8, 8, 7, 9, 9, 6, 7, 9])

4-1. 기본 areaplot 그리기

In [18]:
x = np.arange(1,21)
y =  np.random.randint(low=5, high=10, size=20)

# fill_between으로 색칠하기
plt.fill_between(x, y, color="green", alpha=0.6)
plt.show()

4-2. 경계선을 굵게 그리고 area는 옅게 그리는 효과 적용

In [19]:
plt.fill_between( x, y, color="green", alpha=0.3)
plt.plot(x, y, color="green", alpha=0.8)
Out[19]:
[<matplotlib.lines.Line2D at 0x7ffb80cd54a8>]

4-3. 여러 그래프를 겹쳐서 표현

In [63]:
x = np.arange(1, 10, 0.05)
y_1 =  np.cos(x)+1
y_2 =  np.sin(x)+1
y_3 = y_1 * y_2 / np.pi

plt.fill_between(x, y_1, color="green", alpha=0.1)
plt.fill_between(x, y_2, color="blue", alpha=0.2)
plt.fill_between(x, y_3, color="red", alpha=0.3)
Out[63]:
<matplotlib.collections.PolyCollection at 0x7ffb801cd470>

5. Histogram

5-1. 기본 Histogram 그리기

In [20]:
N = 100000
bins = 30

x = np.random.randn(N)
y = .4 * x + np.random.randn(100000) + 5

plt.hist(x, bins=bins)

plt.show()
  • sharey: y축을 다중 그래프가 share
  • tight_layout: graph의 패딩을 자동으로 조절해주어 fit한 graph를 생성

5-2. 다중 Histogram 그리기

In [21]:
N = 100000
bins = 30

x = np.random.randn(N)
y = .4 * x + np.random.randn(100000) + 5

fig, axs = plt.subplots(1, 2, 
                        sharey=True, 
                        tight_layout=True
                       )

axs[0].hist(x, bins=bins)
axs[1].hist(y, bins=bins)

plt.show()
/opt/conda/lib/python3.6/site-packages/matplotlib/figure.py:2369: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
  warnings.warn("This figure includes Axes that are not compatible "

5-3. Y축에 Density 표기

In [22]:
N = 100000
bins = 30

x = np.random.randn(N)
y = .4 * x + np.random.randn(100000) + 5

fig, axs = plt.subplots(1, 2, 
                        sharey=True, 
                        tight_layout=True
                       )

# density=True 값을 통하여 Y축에 density를 표기할 수 있습니다.
axs[0].hist(x, bins=bins, density=True)
axs[1].hist(y, bins=bins, density=True)

plt.show()

6. Pie Chart

pie chart 옵션

  • explode: 파이에서 툭 튀어져 나온 비율
  • autopct: 퍼센트 자동으로 표기
  • shadow: 그림자 표시
  • startangle: 파이를 그리기 시작할 각도

texts, autotexts 인자를 리턴 받습니다.

texts는 label에 대한 텍스트 효과를

autotexts는 파이 위에 그려지는 텍스트 효과를 다룰 때 활용합니다.

In [23]:
labels = ['Samsung', 'Huawei', 'Apple', 'Xiaomi', 'Oppo', 'Etc']
sizes = [20.4, 15.8, 10.5, 9, 7.6, 36.7]
explode = (0.3, 0, 0, 0, 0, 0)

# texts, autotexts 인자를 활용하여 텍스트 스타일링을 적용합니다
patches, texts, autotexts = plt.pie(sizes, 
                                    explode=explode, 
                                    labels=labels,  
                                    autopct='%1.1f%%',
                                    shadow=True, 
                                    startangle=90)

plt.title('Smartphone pie', fontsize=15)

# label 텍스트에 대한 스타일 적용
for t in texts:
    t.set_fontsize(12)
    t.set_color('gray')
    
# pie 위의 텍스트에 대한 스타일 적용
for t in autotexts:
    t.set_color("white")
    t.set_fontsize(18)

plt.show()

7. Box Plot

샘플 데이터를 생성합니다.

In [24]:
# 샘플 데이터 생성
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low))

7-1 기본 박스플롯 생성

In [25]:
plt.boxplot(data)
plt.tight_layout()
plt.show()

7-2. 다중 박스플롯 생성

In [26]:
# 샘플 데이터 생성
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low))

spread = np.random.rand(50) * 100
center = np.ones(25) * 40

flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100

d2 = np.concatenate((spread, center, flier_high, flier_low))

data.shape = (-1, 1)
d2.shape = (-1, 1)

data = [data, d2, d2[::2,0]]

boxplot()으로 매우 쉽게 생성할 수 있습니다.

다중 그래프 생성을 위해서는 data 자체가 2차원으로 구성되어 있어야 합니다.

row와 column으로 구성된 DataFrame에서 Column은 X축에 Row는 Y축에 구성된다고 이해하시면 됩니다.

In [27]:
plt.boxplot(data)
plt.show()

7-3. Box Plot 축 바꾸기

vert=False 옵션을 통해 표시하고자 하는 축을 바꿀 수 있습니다.

In [28]:
plt.title('Horizontal Box Plot', fontsize=15)
plt.boxplot(data, vert=False)

plt.show()

7-4. Outlier 마커 심볼과 컬러 변경

In [29]:
outlier_marker = dict(markerfacecolor='r', marker='D')
In [30]:
plt.title('Changed Outlier Symbols', fontsize=15)
plt.boxplot(data, flierprops=outlier_marker)

plt.show()

댓글남기기