데이터 분석/시각화

[시각화] matplotlib

eunnys 2023. 11. 3. 14:40

■ Marker Style 종류

 

character description character description
' . ' point marker ' s ' square marker
' , ' pixel marker ' p ' pentagon marker
' o ' circle marker ' * ' star marker
' v ' triangle_down marker ' h ' hexagon1 marker
' ^ ' triangle_up marker ' H ' hexagon2 marker
' < ' triangle_left marker ' + ' plus marker
' > ' triangle_right marker ' x ' x marker
' 1 ' tri_down marker ' D ' diamond marker
' 2 ' tri_up marker ' d ' thin_diamond marker
' 3 ' tri_left marker ' | ' vline marker
' 4 ' tri_right marker ' _ ' hline marker

 

 

■ Line Style 종류

 

character description
' - ' solid line style
' -- ' dashed line style
' -. ' dash-dot line style
' : ' dotted line style

 

 

■ Colors 종류

 

character description
' b ' blue
' g ' green
' r ' red
' c ' cyan
' m ' magenta
' y ' yellow
' k ' black
' w ' white

 

 

import numpy as np

x = np.linspace(0, 2*np.pi, 100) # 0에서 2*pi까지 100개로 균등분할

# 적색 선, 원형 마커, 실선 / 녹색 선, 삼각형 마커, 실점선 / 청색 선, 가위표 마커, 점선
plt.plot(x, np.sin(x), 'ro--', x, np.cos(x), 'g^-.', x, -np.sin(x), 'bx:')
plt.xlim(0, 2*np.pi) # x축 범위 지정
plt.show()

 

 

t = np.arange(0., 5., 0.2) # 0에서부터 5까지 0.2씩 증가

plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^:')
plt.show()

 

 

x = np.arange(10)
y = np.random.randint(0, 100, 10) # 0에서 100 사이의 값을 10개 추출

plt.plot(x, y, c='b', lw=3, ls=':', marker='o', ms=10, mec='r', mew=2, mfc='y')
plt.title('Various Style')
plt.show()

 

 

제목 표시하기


- title() 함수를 이용해 그림의 제목을 표시할 수 있다.
- xlable(), ylable() 함수를 이용해서 각각 x축의 이름과 y축의 이름을 표시할 수 있다.
- lablepad : 축 레이블의 여백 지정 (단위: pt)

 

plt.plot(['Jan', 'Feb', 'March'], [104.8, 72.9, 134.5])
plt.title('Monthly Sales Graph')
plt.xlabel('Month', labelpad=10)
plt.ylabel('Sales', labelpad=20)
plt.show()

 

 

 

범례 표시하기


- plot() 함수에 label 키워드 인자를 설정함으로써 그래프의 이름을 지정할 수 있다.
- 이렇게 지정된 이름은 legend() 함수를 통해 범례로써 표시할 수 있다.
- loc 파라미터에 튜플로 2개의 값을 지정하면 해당 위치에 범례가 표시가 되어진다.

    'best'
    'upper right'
    'upper left'
    'lower left'
    'lower right'
    'right'
    'center left'
    'center right'
    'lower center'
    'upper center'
    'center'

 

a = np.arange(0, 3, 0.02)
c = np.exp(a) # 지수 함수
d = c[::-1] # c를 뒤집음

plt.plot(a, c, 'r--', label='Model length')
plt.plot(a, d, 'b:', label='Data length')
plt.plot(a, c+d, 'g', label='Total message length')

plt.legend(loc='best', shadow=True)
plt.show()

 

 

 축 눈금 지정하기


- xticks(), yticks() 함수를 통해 각 축의 눈금을 지정할 수 있다.

 

plt.plot([1, 3, 2, 4]) # x는 1씩 증가된 값 사용
plt.show()

 

 

plt.plot([1, 3, 2, 4]) # x는 1씩 증가된 값 사용
plt.xticks(np.arange(0, 2, 0.5))
plt.show()

 

 

plt.plot([1, 3, 2, 4]) # x는 1씩 증가된 값 사용

# xticks(표시할 눈금 x값 위치(인덱스), 명칭, 회전 각도 설정)
plt.xticks([0, 1, 2, 3], ['January', 'February', 'March', 'April'], rotation=30)
plt.show()

 

 

plt.plot([1, 3, 2, 4]) # x는 1씩 증가된 값 사용
plt.xticks([]) # 눈금 삭제
plt.show()

 

 

 

Figure 객체


- Figure 클래스는 plot에 필요한 모든 요소를 가지고 있는 최상위 클래스이다.
- figure() 함수는 Figure 객체를 반환한다.
- 여러 개의 윈도우를 동시에 띄어야 하거나, 그림의 크기를 설정해야 할 때 주로 사용한다.

 

# 기본 그림 크기 : [6.4, 4.8], inch 단위
print(plt.rcParams['figure.figsize'])

 

import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=(10, 3)) # 그림의 크기 값 지정
x = [1, 3, 5, 8, 12]
y = np.power(x, 3) # 지수 연산 x에 있는 값을 각각 3승

plt.plot(x, y, 'go--')
plt.show()

 

 

 

subplot 그리기

 

- subplot() 함수를 이용해서 하나의 figure에 여러 개의 그래프를 그릴 수 있다.
- 주요 인자 : nrows, ncols, index를 지정하는 3개의 정수를 이용하여 subplot의 위치를 지정할 수 있다.

 

x1 = np.linspace(0.0, 5.0) # 분할할 데이터의 수를 입력하지 않으면 default 값은 50
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
 
plt.subplot(2, 1, 1) # nrows=2, ncols=1, index=1 (2행 1열 중에 첫 번째 그래프)
plt.plot(x1, y1, 'o-')
plt.title('1st Graph')
plt.xlabel('time (s)')
plt.ylabel('Damped')

plt.subplot(2, 1, 2) # 2행 1열 중에 두 번째 그래프
plt.plot(x2, y2, '.-')
plt.title('2nd Graph')
plt.xlabel('time (s)')
plt.ylabel('Undamped')

plt.tight_layout() # subplot의 레이아웃을 자동으로 맞춰준다
plt.show()

 

 

 

■ subplots 그리기

 

- subplots() 힘수를 이용해서 subplot을 그릴 수 있다.
- subplots() 함수는 Figure와 Axes 객체를 반환한다.
  - Axes 클래스 : 공긴이 확보된 이미지의 영역정보를 가지고 있다.
- 주요 인자
  - nrows, ncols : subplot의 행과 열값 지정
  - sharex, sharey : boolean 값 (default:False) x, y축 사이의 공유 제어 속성

 

fig, axes = plt.subplots(1, 4, sharey=True)
fig.set_size_inches((16, 4))  # figure의 크기를 설정

axes[0].scatter(np.random.random(100), np.random.random(100), color='cyan', edgecolor='red', alpha=0.5)      # 1번째 열
axes[1].scatter(np.random.random(100), np.random.random(100), color='magenta', edgecolor='green', alpha=0.5) # 2번째 열
axes[2].scatter(np.random.random(100), np.random.random(100), color='yellow', edgecolor='blue', alpha=0.5)   # 3번째 열
axes[3].scatter(np.random.random(100), np.random.random(100), color='white', edgecolor='black', alpha=0.5)   # 4번째 열

axes[0].set_title('subplot 0')
axes[1].set_title('subplot 1')
axes[2].set_title('subplot 2')
axes[3].set_title('subplot 3')
plt.show()

 

 

fig, axes = plt.subplots(2, 2)#, sharey=True)
fig.set_size_inches((16, 8))  # figure의 크기를 설정

axes[0][0].scatter(np.random.random(100), np.random.random(100), color='cyan', edgecolor='red', alpha=0.5)      # 1번째 열
axes[0][1].scatter(np.random.random(100), np.random.random(100), color='magenta', edgecolor='green', alpha=0.5) # 2번째 열
axes[1][0].scatter(np.random.random(100), np.random.random(100), color='yellow', edgecolor='blue', alpha=0.5)   # 3번째 열
axes[1][1].scatter(np.random.random(100), np.random.random(100), color='white', edgecolor='black', alpha=0.5)   # 4번째 열

axes[0][0].set_title('subplot 0')
axes[0][1].set_title('subplot 1')
axes[1][0].set_title('subplot 2')
axes[1][1].set_title('subplot 3')
plt.show()

 

 

 

■ 막대 그래프 그리기


- bar() 함수를 이용해서 막대 그래프를 그릴 수 있다.

 

x1 = np.arange(0, 20) # 0에서 19까지
y1 = x1*2

x_ticks = np.arange(len(x1))

plt.bar(x1, y1, label='Blue bar', color='blue', edgecolor='yellow', linewidth=3)
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Bar Chart Example')
plt.xticks(x_ticks, x_ticks+1) # 1에서 20까지
plt.legend()
plt.show()

 

 

- barh() 함수를 이용해서 수평 막대 그래프를 그릴 수 있다.

 

x1 = np.arange(0, 20) # 0에서 19까지
y1 = x1*2

x_ticks = np.arange(len(x1))

# 수평 막대 그래프를 그린다고 해서 x와 y의 위치가 바뀌는 건 아니다
plt.barh(x1, y1, label='Blue bar', color='blue', edgecolor='yellow', linewidth=3)
plt.xlabel('bar height')
plt.ylabel('bar number')
plt.title('Bar Chart Example')
plt.yticks(x_ticks, x_ticks+1) # 1에서 20까지
plt.legend()
plt.show()

 

 

 

matplotlib 색상표

 

 

 

labels = ['Seoul', 'Busan', 'Incheon', 'Gwangju', 'Jeju']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x_ticks = np.arange(len(men_means))
width = 0.35 # 막대 그래프의 폭 크기

# 하나의 눈금에 2개의 막대 그래프
plt.bar(x_ticks - width / 2, men_means, width=width, color='dodgerblue', label='Men')
plt.bar(x_ticks + width / 2, women_means, width=width, color='violet', label='Women')

plt.xlabel('City')
plt.ylabel('Score')
plt.xticks(x_ticks, labels)
plt.title('Score by group and gender')
plt.legend()
plt.show()

 

 

 

■ 산점도 그리기


- 산점도(scatter plot)은 직교 좌표계를 이용해서 두 변수 간의 상관관계를 나타내는 plot이다.
- scatter() 함수를 이용해서 산점도를 그릴 수 있다.

 

np.random.seed(0)
for color in ['blue', 'orange', 'green']:
    n = 50 # 랜덤한 값 50개
    x, y = np.random.rand(2, n) # 0이상 1미만 사이의 난수를 2 X 50 모양으로 생성 (2행 50열: 첫 번째 행은 x값, 두 번째 행은 y값)
    scale = 190 * np.random.rand(n) + 10 # 10이상 200미만 사이의 난수 50개 생성
    plt.scatter(x, y, color=color, s=scale, label=color, alpha=0.3, edgecolor='none') # alpha() : 투명도

plt.legend() # loc값의 default는 'best'
plt.grid(True) # 격자무늬
plt.show()

 

 

 

히스토그램 그리기


- hist() 함수를 이용해서 히스토그램을 그릴 수 있다.
- 자료의 분포를 몇 개의 구간으로 나눈 후 각 구간에 해당하는 데이터의 빈도수를 표로 나타낸 것을 도수분포표(Frequency table)라고 한다.
- 히스토그램은 도수분포표에서 구간별 빈도수를 막대 그래프로 나타낸 것이다.

 

y = np.random.randn(1000) # 표준정규분포로 난수 1000개 생성 (평균이 0, 표준편차는 1)
x = np.arange(len(y))
plt.bar(x, y)
plt.title('Raw Data <Bar chart>')
plt.show()

plt.hist(y, bins=50) # bins=50 : 표현할 데이터를 50개의 구간으로 나눈다
plt.title('Histogram')
plt.show()

plt.hist(y, cumulative=True, bins=20) # 누적도수분포표를 만든다
plt.title('Cumulative Histogram')
plt.show()

 

 

 

■ 원 그래프 그리기


- pie() 함수를 이용해서 원 그래프를 그릴 수 있다.

 

labels = ['Python', 'Java', 'C']
# autopct : 파이의 각 조각(wedge) 위에 표시할 레이블 (default:None)
# pie() 함수에 전달하는 값은 굳이 비율 값을 전달하지 않고, 일반적인 값을 전달하더라도 값들의 총합에 대한 비율을 알아서 계산해줌
plt.pie([0.3, 0.35, 0.4], labels=labels, autopct='%.1f%%')
plt.title('Popular Language Ranking')
plt.show()
# 데이터는 3시 방향부터 시작해서 반시계 방향으로

 

sections = [0.3, 0.35, 0.4]
labels = ['Python', 'Java', 'C']
colors = ['coral', 'dodgerblue', 'yellowgreen']

plt.pie(
    sections, # 조각의 크기를 설정하는 기본값
    explode=(0.1, 0, 0), # 조각을 중심으로부터 얼마나 떨어지게 할 것인지 설정 (0.1: 반지름의 10% 만큼 벗어남)
    colors=colors, # 조각의 색깔을 설정
    labels=labels, # 조각의 이름을 표시
    autopct='%.2f%%', # 비율을 표시 (소수점 이하 2자리까지 % 문자열 표시)
    shadow=True, # 그림자를 표시
    startangle=90, # 첫번째 조각의 각도 표시 (default:3시 방향, 0도)
    counterclock=False, # 반시계 방향으로 표시할지 여부 (default:True)
    rotatelabels=True, # 조각의 이름을 회전 (default:False)
)
plt.title('Pie Chart Example 2')
plt.show()

 

 

 

■ boxplot 그리기


- boxplot은 데이터 집합의 범위와 중앙값 등 통계 수치를 확인하고 데이터의 이상치를 확인하고자 하는 목적으로 사용한다.
- 최소값 : 제 1사분위에서 1.5IGR(Interquantile range:사분위수 범위, Q3-Q1)을 뺀 위치
- 제 1사분위(Q1) : 중앙값 기준으로 하위 50% 중의 중앙값 (전체 데이터 중 하위 25%)
- 제 2사분의(Q2) : 50%의 위치로 중앙값(median)을 의미. 데이터의 정 가운데 순위에 해당하는 값
- 제 3사분의(Q3) : 중앙값 기준으로 상위 50% 중의 중앙값 (전체 데이터 중 상위 25%)
- 최대값 : 제 3사분위에서 1.5IQR을 더한 위치
- IQR(Interquantile range, 사분위수 범위) = Q3 - Q1
- 최대값고ㅘ 최소값 범위를 벗어나는 값을 이상치 데이터로 간주한다.

 

np.random.seed(0)

data_a = np.random.normal(0, 2.0, 1000) # 평균은 0이고 표준편차는 2에 해당하는 데이터 1000개
data_b = np.random.normal(-3, 1.5, 500) # 평균은 -3이고 표준편차는 1.5에 해당하는 데이터 500개
data_c = np.random.normal(1.2, 1.5, 1500) # 평균은 1.2이고 표준편차는 1.5에 해당하는 데이터 1500개

plt.boxplot([data_a, data_b, data_c])
plt.ylim(-10, 10) # y축의 범위
plt.xlabel('Data Type')
plt.ylabel('Value')
plt.show()