본문 바로가기
코딩 수업/포트폴리오

[업무 자동화][파이썬] 시험 점수로 그래프 만드는 프로그램 (Python Program for Visualizing Student Score Trends Across Lessons and Units)

by Jade S. 2025. 3. 6.
728x90
반응형

기능 설명:

이 프로그램은 각 학생의 영어 수업 점수 변화를 시각화하는 도구로, 주요 기능은 다음과 같습니다:

  1. 엑셀 데이터 처리:
    • 엑셀 파일에서 학생의 이름, 단원(Unit), 수업(Lesson), 점수(Score)를 읽어와, 각 학생의 수업을 연속된 번호(Global_Lesson)로 변경하여 점수 변화를 시간 흐름에 맞게 표시합니다.
  2. 그래프 생성:
    • 각 학생의 점수 추이를 선 그래프 형식으로 표시하며, Lesson 4(unit test) 점수는 핑크색 마커로 강조됩니다.
    • 새로운 단원이 시작되는 지점은 초록색 점선으로 표시됩니다.
  3. 학생별 성과 표시:
    • 그래프에 학생의 평균 점수100점 횟수를 우측에 표시하여 성과를 직관적으로 나타냅니다.
  4. 시각화 설정:
    • X축에 수업 번호를, Y축에 점수를 표시하며, 각 학생별로 별도의 그래프가 생성됩니다.
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib

# 한글 폰트 설정
matplotlib.rcParams['font.family'] = 'Malgun Gothic'  # Windows에서 사용할 수 있는 한글 폰트

# 엑셀 파일 경로
file_path = "엑셀파일경로"

# 엑셀 파일 읽기
df = pd.read_excel(file_path)

# Lesson을 연속된 번호로 변경 (학생별로 순차적으로 증가)
df['Global_Lesson'] = df.groupby('Name').cumcount() + 1

# 각 학생 처리
students = df['Name'].unique()

for student in students:
    student_data = df[df['Name'] == student]

    # 점수가 없는 부분 제거
    student_data = student_data.dropna(subset=['Score'])

    # 새로운 Unit 1과 Lesson 1이 동시에 시작되는 지점 찾기
    new_unit1_starts = student_data[(student_data['Unit'] == 1) & (student_data['Lesson'] == 1)]['Global_Lesson']

    # 선 그래프 그리기
    plt.figure(figsize=(8, 5))
    plt.plot(student_data['Global_Lesson'], student_data['Score'], marker='o', label="Score Trend")

    # Lesson 4 강조: 빨간색 마커와 더 큰 마커
    lesson4 = student_data[student_data['Lesson'] == 4]
    plt.scatter(lesson4['Global_Lesson'], lesson4['Score'], color='hotpink', s=100, label='Unit Test (Lesson 4)', zorder=5)

    # 새로운 Unit 1 시작 지점에 세로선 추가
    for start in new_unit1_starts:
        plt.axvline(x=start, color='green', linestyle='--', linewidth=1.5, label='New Book Start')

    # 그래프 제목에 이름 포함 (폰트 사이즈 키움)
    plt.title(f"Score Trend for {student} Across Units", fontsize=20)

    # 그래프 꾸미기
    plt.xlabel("Lesson", fontsize=12)
    plt.ylabel("Score", fontsize=12)
    plt.xticks(student_data['Global_Lesson'], labels=[f"U{u}L{l}" for u, l in zip(student_data['Unit'], student_data['Lesson'])])
    plt.legend()
    plt.grid()

    # Y축 범위 설정
    plt.ylim(0, 110)

    # 우측 여백을 만들어 평균 점수와 100점 횟수 표시
    plt.subplots_adjust(right=0.75, bottom=0.1)  # right 값 줄여서 여백 더 줄임

    # 평균 점수 계산
    average_score = student_data['Score'].mean()

    # 100점 횟수 계산
    perfect_scores = (student_data['Score'] == 100).sum()

    # 평균 점수 추가 (형식 변경: "평균:**점") (글씨 크기 증가)
    plt.text(1.05, 0.12, f"평균: {average_score:.2f}점", fontsize=18, verticalalignment='bottom', horizontalalignment='left', transform=plt.gca().transAxes,
             bbox=dict(facecolor='white', edgecolor='none', pad=0))

    # 100점이 있을 경우에만 "100점 횟수" 추가 (글씨 크기 증가)
    if perfect_scores > 0:
        plt.text(1.05, 0.06, f"100점: {perfect_scores}회", fontsize=18, verticalalignment='bottom', horizontalalignment='left', transform=plt.gca().transAxes,
                 bbox=dict(facecolor='white', edgecolor='none', pad=0))

    # 그래프 출력
    plt.show()

 

결과물:

728x90
반응형