Python/seaborn, matplotlib

matplotlib.pylot으로 그래프 그리기

얆생 2023. 4. 15. 16:51

matplotlib으로 간단한 그래프를 그려보자

 

  • matplotlib 불러오고 임의의 데이터 만들어주기
import matplotlib.pyplot as plt

customers = ['abc', 'def', 'ghi', 'jkl', 'mno']
customers_index = range(len(customers))
sale_amounts = [127, 90, 201, 111, 232]

 

 

  • barplot 그리기
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)   #하위 그래프의 행과 열 지정, (1,1,1)은 ax1이 유일한 하위그래프임을 의미
ax1.bar(customers_index, sale_amounts, align='center', color='dark blue') #막대가 레이블 중앙에 위치하도록

ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left') #눈금이 각각 아래쪽, 왼쪽에 오도록

plt.xticks(customers_index, customers, rotation=0, fontsize='large')
plt.xlabel('Customer Name')
plt.ylabel('Sale Amount')
plt.title('Sale Amount per Customer')

plt.savefig('bar_plot.png', dpi=400, bbox_inches='tight')
plt.show()

 

 

* plt.xticks(눈금을 적용할 x축의 위치, 해당 위치에 나타낼 값, rotation=각도조절, fontsize= 숫자 또는 '사이즈 직접 지정')

* fontsize 종류: xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, None

* plt.xlabel / plt.ylabel / plt.title('라벨 이름, 그래프 제목')

* plt.savefig('파일제목.png', dpi=해상도, bbox_inches='tight' >> 그림 둘러싼 여백 제거)

* plt.show() 필수

 

 

 

  • numpy 불러오고, random 모듈을 이용해 정규분포 따르는 두 개의 변수 만들어주기
import numpy as np

mu1, mu2, sigma = 100, 130, 15
x1 = mu1 + sigma*np.random.randn(10000)
x2 = mu2 + sigma*np.random.randn(10000)

 

*python random 모듈

- np.random.randint() : 균일 분포의 정수 난수 1개 생성

- np.random.rand() : 0부터 1사이의 균일 분포에서 난수 matrix array 생성

- np.random.randn(): 가우시안 표준 정규 분포에서 난수 matrix array 생

 

 

  • histogram 그리기
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

n, bins, patches = ax1.hist(x1, bins=50, color='darkgreen')
n, bins, patches = ax1.hist(x2, bins=50, color='orange', alpha=0.5)
ax1.xaxis_ticks_position('bottom')
ax1.yaxis_ticks_position('left')

plt.xlabel('Bins')
plt.yalbel('Numbers of Values in Bin')
fig.suptitle('Histogram', fontsize=14, fontweight='bold')
plt.title('Two Frequency Distributions')
plt.savefig('histogram.png', dpi=400, bbox_inches='tight')
plt.show()

 

* n, bins, patches = plt.hist() : 관측치 개체를 별도로 할당

   - alpha = 투명도 설정, 0에 가까워질수록 투명

 

* fontweight = 폰트 두께 설정

 

 

 

  • numpy random모듈의 randn으로 임의의 데이터 만들기
from numpy.random import randn

plot_data1 = randn(50).cumsum()
plot_data2 = randn(50).cumsum()
plot_data3 = randn(50).cumsum()
plot_data4 = randn(50).cumsum()

 

* cumsum() : 배열에서 주어진 축에 따라 누적되는 원소들의 누적합을 계산 하는 함수

   ex) a = np.array( [ [1,2,3], [4,5,6] ] )

         print(np.cumsum(a))

         >>> [ 1 3 6 10 15 21 ]

 

 

  • Lineplot 그리기
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

ax1.plot(plot_data1, marker=r'o', color = u'blue', linestyle='-', label='Blue Solid')
ax1.plot(plot_data2, marker=r'+', color = u'red', linestyle='--', label='Red Dashed')
ax1.plot(plot_data3, marker=r'*', color = u'green', linestyle='-', label='Green Dash Shot')
ax1.plot(plot_data4, marker=r's', color = u'orange', linestyle=':', label='Orange Dotted')
ax1.xaxis_ticks_position('bottom')
ax1.yaxis_ticks_position('left')

plt.xlabel('Draw')
plt.ylabel('Random Number')
plt.title('Line Plot: Markers, colors, and Linestyles')
plt.legend(loc='best')
plt.savefig('line_plot.png', dpi=400, bbox_inches='tight')
plt.show()

 

* plt.plot(data, marker= , color= , linestyle= , label= )

  - marker = 마커 모양 ex) 'o'    ','   '^'   '<'   '>'   '*'   '+'  'v'   '8'   's'  'p'   'h'   'D'   '.'

(https://matplotlib.org/stable/api/_as_gen/matplotlib.markers.MarkerStyle.html) 

- color = 색 지정  ex) 'b'  'g'   'r'   'c'   'm'   'y'   'k'   'w' 

- linestyle = 선 모양 ex) '-'   '--'   '-.'   ':'   'None' (https://matplotlib.org/stable/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D.set_linestyle)

  - label = 라벨 지정

 

 

 

 

* 간단하게 그리기

- plt.plot(data, 'bo-') >> 파란색, 마커는 원 모양, 선 스타일은 -로 한번에 지정 가능

ax1.plot(plot_data1, 'bo-')
ax1.plot(plot_data2, 'r+--')
ax1.plot(plot_data3, 'g*-')
ax1.plot(plot_data4, 'ks:')

 

 

 

  • 선형다항식 및 2차 다항식 만들기
import numpy as np

x = np.arange(start=1., stop=15., step=1.)

y_linear = x + 5. * np.random.randn(14)  #다항식의 데이터 임의로 만들기
y_quadratic = x**2 + 10. * np.random.randn(14)

fn_linear = np.poly1d(np.polyfit(x, y_linear, deg=1))  #좌표쌍들에 대해 선형 및 2차 다항식 만들기
fn_quadratic = np.poly1d(np.polyfit(x, y_quadratic, deg=2))

 

* np.arange(시작점, 끝점, step size) : 특정 수열을 만들려고 할 때 많이 사용

                                                           : 실행 결과의 수열은 numpy array 형태의 자료형에 들어가있음

                                                           : range는 정수 단위만 지원하지만 arange는 실수 단위도 표현 가능

* poly1d(입력 배열, 근 설정, 변수명): 다항식 생성 함수

* ployfit(x, y, n): 주어진 데이터에 대해 최소 제곱을 갖는 다항식 피팅을 반환함

                        : x는 data의 input값, y는 input값에 해당하는 output값, n(deg)은 다항식 차수

 

 

  • scatterplot 그리기
fig = plt.figure()
ax1 = fid.add_subplot(1,1,1)
ax1.plot(x, y_linear, 'bo', x, y_quadratic, 'go', x, fn_linear(x), 'b-', x, fn_quadratic(x), 'g-', linewidth=2.)

ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
ax1.set_title('Scatter Plots with Best Fit Lines')
plt.xlabel('x')
plt.ylabel('f(x)')

plt.xlim((min(x)-1., max(x)+1.))
plt.ylim((min(y_quadratic)-10, max(y_quadratic)+10.))
plt.savefig('scatter_plot.png', dpi=400, bbox_inches='tight')
plt.show()

 

* 축 범위 지정하기

  - plt.xlim((xmin, xmax)): xmin, xmax 값을 각각 입력하거나 리스트 또는 튜플의 형태로 입력, x축이 표시되는 범위를 지정하거나 반환

  - plt.ylim((ymin, ymax))

 

 

 

  • boxplot 그리기
N = 500
normal = np.random.normal(loc=0.0, scale=1.0, size = N)
lognormal = np.random.lognormal(mean=0.0, sigma=1.0, size=N)
index_value = np.random.random_integers(low=0, high=N-1, size=N)
normal_sample = normal[index_value]
lognormal_sample = lognormal[index_value]
box_plot_data = [normal, normal_sample, lognormal, lognormal_sample]

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
box_labels = ['normal', 'normal_sample', 'lognormal', 'lognormal_sample']
ax1.boxplot(box_plot_data, notch=False, sym='.', vert=True, whis=1.5, showmeans=True, labels=box_labels)

ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
ax1.set_title('Box Plots: Resampling of Two Distributions')
ax1.set_xlabel('Distribution')
ax1.set_ylabel('Value')

plt.savefig('box_plot.png', dpi=400, bbox_inches='tight')
plt.show()