Python/Python기초

Python 68_ kNN iris - matplotlib을 이용한 그래프 그리기

Codezoy 2020. 2. 24. 18:40

Python 67_ kNN 직접 구현하기 >> 에 이어서 작업해주시면 됩니다.

# 데이터 프레임을 이용해서 각 특성(변수)들과 Class(레이블)과의 관계 그래프
iris_by_class = iris.groupby(by='Class')
for name, group in iris_by_class:
    # print(name, len(group))
    plt.scatter(group['sepal_length'], group['sepal_width'],
    label=name)
plt.legend()
plt.xlabel('sepal_length')
plt.ylabel('sepal_width')
plt.show()

for name, group in iris_by_class:
    # print(name, len(group))
    plt.scatter(group['petal_length'], group['petal_width'],
    label=name)
plt.legend()
plt.xlabel('petal_length')
plt.ylabel('petal_width')
plt.show()






>> subplots를 이용해 그래프 동시에 여러개 그리기
import matplotlib.pyplot as plt
import pandas as pd

col_names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']
iris = pd.read_csv('iris.csv', header=None, names=col_names)
iris_by_class = iris.groupby(by='Class')


xy = [] # x축/y축에 사용할 변수 이름
ab = []
for i in range(4):
    for j in range(i+1, 4):
        xy.append((col_names[i], col_names[j]))
print(xy)

>> xy
for문을 이용한 순열을 구현하여, 5가지 경우에 대한 조합을 만드는 모습.
[('sepal-length', 'sepal-width'), ('sepal-length', 'petal-length'), ('sepal-length', 'petal-width'), ('sepal-width', 'petal-length'), ('sepal-width', 'petal-width'), ('petal-length', 'petal-width')]

0 1
0 1 2
아래는 화면을 subplots(2 * 3) 행렬로 구성하는 것
    
fig, ax = plt.subplots(2, 3)
xy_idx = 0
    for row in range(2):
        for col in range(3):
            axis = ax[row, col] # axis = ax[row][col]
            x = xy[xy_idx][0] # x축 데이터 이름
            y = xy[xy_idx][1] # y축 데이터 이름
            xy_idx += 1 # 다음 x-y축 데이터 이름으로 이동
            axis.set_title(f'{x} vs {y}') # sub_plot 축의 제목
            axis.set_xlabel(x) # sub_plot 축의 x 레이블
            axis.set_ylabel(y) # sub_plot 축의 y 레이블
            for name, group in iris_by_class:
                axis.scatter(group[x], group[y], label=name)

plt.legend()
plt.show()      
    .
   .