더북(TheBook)

그룹1과 그룹2에 각각 100명씩 있으므로 키와 몸무게를 리스트에 추가하는 명령어를 반복문으로 100번 반복합니다. 산점도를 2개 그려야 하므로 plt.scatter()를 두 번 사용합니다. 그룹1의 산점도는 x축을 height1으로, y축을 weight1으로 하고, 색상은 crimson(진홍색), 투명도는 0.7로 설정합니다. 그룹2의 산점도는 height2weight2를 각각 x축, y축으로 하고, 색상을 indigo(남색), 투명도는 0.7로 설정합니다.

그룹1과 그룹2의 데이터 범위가 다른 것이 보이나요? 대체적으로 진홍색의 그룹1은 그래프의 왼쪽 아래에, 남색의 그룹2는 그래프의 오른쪽 위에 위치합니다. 그리고 가운데 영역에 그룹1과 그룹2가 겹치는 구간이 있고요. 이처럼 산점도는 데이터의 분포를 비교할 때 용이합니다.

이번에는 체육 점수를 추가해 점의 크기까지 설정해 보겠습니다. 그룹1의 체육 점수는 score1, 그룹2의 체육 점수는 score2로 합니다. 그리고 두 그룹 모두 체육 점수 범위는 0~200 사이로 합니다.

height1, weight1, score1, height2, weight2, score2 = [], [], [], [], [], []
for i in range(100):
    height1.append(random.randint(140, 180))
    weight1.append(random.randint(40, 80))
    score1.append(random.randint(0, 200))
    height2.append(random.randint(160, 200))
    weight2.append(random.randint(50, 100))
    score2.append(random.randint(0, 200))

plt.rc('font', family='Malgun Gothic')
plt.title('키와 몸무게, 체육 점수의 상관관계')
plt.scatter(height1, weight1, s=score1, color='crimson', alpha=0.7, label='그룹1')
plt.scatter(height2, weight2, s=score2, color='indigo', alpha=0.7, label='그룹2')
plt.xlabel('키')
plt.ylabel('몸무게')
plt.legend()
plt.show()
실행결과

산점도를 그릴 때 s 옵션을 추가하니 점의 크기가 달라집니다. 이처럼 산점도도 겹쳐서 비교 그래프를 그릴 수 있습니다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.