Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬 matplotlib로 한 페이지에 여러 플롯 그리기 – 단계별 실전 가이드

파이썬에서 matplotlibPandas를 함께 사용하면 데이터프레임을 기반으로 figure(그림)와 axis(축) 객체를 손쉽게 생성하고, scatter 메서드를 이용해 데이터 포인트를 시각화할 수 있습니다. 아래에서는 학생 수와 획득 점수 데이터를 산점도로 표현하는 과정을 단계별로 살펴보고, 나아가 한 페이지에 여러 플롯을 배치하는 방법까지 소개합니다.

구현 단계

  • 학생 수, 각 학생이 획득한 점수, 점수별 색상 코드 목록을 준비합니다.

  • 준비한 데이터를 바탕으로 Pandas의 DataFrame을 사용해 데이터프레임을 생성합니다.

  • subplots 메서드로 figax 변수를 만듭니다. 기본값은 nrows=1, ncols=1입니다.

  • plt.xlabel() 메서드로 X축 레이블을 설정합니다.

  • plt.ylabel() 메서드로 Y축 레이블을 설정합니다.

  • 마커 크기 또는 색상을 다양하게 지정하여 x에 대한 y 산점도(scatter plot)를 그립니다.

  • plt.show() 메서드를 호출해 그래프를 화면에 표시합니다.

예제 코드

from matplotlib import pyplot as plt
import pandas as pd

no_of_students = [1, 2, 3, 5, 7, 8, 9, 10, 30, 50]
marks_obtained_by_student = [100, 95, 91, 90, 89, 76, 55, 10, 3, 19]
color_coding = ['red', 'blue', 'yellow', 'green', 'red',
                'blue', 'yellow', 'green', 'yellow', 'green']

df = pd.DataFrame(dict(students_count=no_of_students,
                       marks=marks_obtained_by_student,
                       color=color_coding))

fig, ax = plt.subplots()

plt.xlabel('Students count')
plt.ylabel('Obtained marks')

ax.scatter(df['students_count'], df['marks'], c=df['color'])

plt.show()

실행 결과

파이썬 matplotlib로 한 페이지에 여러 플롯 그리기 – 단계별 실전 가이드

한 페이지에 여러 플롯 배치하기

subplots 메서드에서 nrowsncols 값을 조정하면 하나의 figure 안에 여러 개의 플롯을 격자 형태로 배치할 수 있습니다. 예를 들어 plt.subplots(nrows=2, ncols=2)처럼 작성하면 2×2 구조로 총 4개의 축이 생성되며, 이때 반환되는 ax는 배열이므로 인덱스를 통해 각 플롯에 개별적으로 접근할 수 있습니다.

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))

axes[0, 0].scatter(df['students_count'], df['marks'], c=df['color'])
axes[0, 0].set_title('Scatter Plot')
axes[0, 1].plot(df['students_count'], df['marks'])
axes[0, 1].set_title('Line Plot')
axes[1, 0].bar(df['students_count'], df['marks'])
axes[1, 0].set_title('Bar Chart')
axes[1, 1].hist(df['marks'], bins=5)
axes[1, 1].set_title('Histogram')

plt.tight_layout()
plt.show()

이처럼 subplots의 행·열 옵션을 활용하면 서로 다른 유형의 차트를 한눈에 비교할 수 있는 대시보드 스타일의 시각화를 간단히 구성할 수 있습니다. 마지막에 plt.tight_layout()을 호출하면 플롯 간 간격이 자동으로 조절되어 제목이나 축 레이블이 겹치는 문제를 방지할 수 있습니다.