📊 실생활 데이터를 DataFrame으로 만들고 그래프 출력하기

한글 깨짐 방지 설정 포함 · 에러/경고 최소화 코드 구성
직선 그래프 10개 + 막대 그래프 10개 + 이중 y축 혼합 그래프 5개

공통 한글 깨짐 방지 코드
모든 예제에는 plt.rcParams["font.family"]plt.rcParams["axes.unicode_minus"] = False가 들어 있습니다.
이중 y축 그래프는 fig, ax1 = plt.subplots()로 왼쪽 축을 만들고, ax2 = ax1.twinx()로 오른쪽 축을 추가합니다.
직선 그래프

1. 1. 일주일 평균 기온 변화

실선, 원형 마커, 평균선, 최고점 주석을 조합한 직선 그래프입니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'요일': ['월', '화', '수', '목', '금', '토', '일'], '기온': [18, 19, 21, 20, 23, 24, 22]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["요일"], df["기온"],
         color="royalblue", marker="o", linewidth=3, markersize=8, label="평균 기온")
plt.axhline(df["기온"].mean(), color="gray", linestyle=":", label="평균선")
plt.annotate("최고 기온", xy=("토", 24), xytext=("금", 25),
             arrowprops=dict(arrowstyle="->"))
plt.title("1. 일주일 평균 기온 변화")
plt.xlabel("요일")
plt.ylabel("기온(℃)")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
1. 일주일 평균 기온 변화
직선 그래프

2. 2. 월별 전기 사용량 변화

점선, 사각형 마커, 투명도, 평균선을 결합했습니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'월': ['1월', '2월', '3월', '4월', '5월', '6월'], '전기사용량': [210, 198, 185, 176, 190, 230]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["월"], df["전기사용량"],
         color="tomato", linestyle="--", marker="s", linewidth=3, alpha=0.85, label="전기 사용량")
plt.axhline(df["전기사용량"].mean(), color="gray", linestyle=":", label="평균선")
plt.title("2. 월별 전기 사용량 변화")
plt.xlabel("월")
plt.ylabel("전기사용량(kWh)")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
2. 월별 전기 사용량 변화
직선 그래프

3. 3. 하루 물 섭취량 누적

파선, 다이아몬드 마커, 면적 채우기, 값 표시를 조합했습니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'시간': ['8시', '10시', '12시', '14시', '16시', '18시'], '물섭취량': [200, 450, 700, 950, 1200, 1500]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["시간"], df["물섭취량"],
         color="deepskyblue", linestyle="-.", marker="D", linewidth=2.5, label="누적 섭취량")
plt.fill_between(df["시간"], df["물섭취량"], alpha=0.18)
for x, y in zip(df["시간"], df["물섭취량"]):
    plt.text(x, y, str(y), ha="center", va="bottom")
plt.title("3. 하루 물 섭취량 누적")
plt.xlabel("시간")
plt.ylabel("물섭취량(mL)")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
3. 하루 물 섭취량 누적
직선 그래프

4. 4. 시험 전 공부 시간 변화

굵은 선, 삼각형 마커, 급증 지점 주석을 사용했습니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'남은날짜': ['D-5', 'D-4', 'D-3', 'D-2', 'D-1'], '공부시간': [2, 3, 4, 5, 7]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["남은날짜"], df["공부시간"],
         color="purple", marker="^", linewidth=5, markersize=9, label="공부 시간")
plt.annotate("공부 시간 급증", xy=("D-1", 7), xytext=("D-2", 8),
             arrowprops=dict(arrowstyle="->"))
plt.title("4. 시험 전 공부 시간 변화")
plt.xlabel("남은날짜")
plt.ylabel("공부시간")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
4. 시험 전 공부 시간 변화
직선 그래프

5. 5. 카페 방문자 수 변화

별 마커와 주말 급증 주석을 활용했습니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'요일': ['월', '화', '수', '목', '금', '토', '일'], '방문자수': [80, 95, 100, 110, 150, 210, 190]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["요일"], df["방문자수"],
         color="darkorange", marker="*", linewidth=2.8, markersize=13, label="방문자 수")
plt.annotate("주말 방문자 급증", xy=("토", 210), xytext=("금", 225),
             arrowprops=dict(arrowstyle="->"))
plt.title("5. 카페 방문자 수 변화")
plt.xlabel("요일")
plt.ylabel("방문자수")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
5. 카페 방문자 수 변화
직선 그래프

6. 6. 스마트폰 사용 시간 변화

소수 데이터, 기준선, 원형 마커를 조합했습니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'날짜': ['1일', '2일', '3일', '4일', '5일', '6일'], '사용시간': [3.2, 4.1, 2.8, 5.0, 4.6, 3.7]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["날짜"], df["사용시간"],
         color="crimson", marker="o", linewidth=2.5, markersize=8, label="사용 시간")
plt.axhline(4, color="green", linestyle="--", label="권장 기준 4시간")
plt.title("6. 스마트폰 사용 시간 변화")
plt.xlabel("날짜")
plt.ylabel("사용시간")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
6. 스마트폰 사용 시간 변화
직선 그래프

7. 7. 버스 평균 대기 시간

얇은 선, x 마커, 최댓값 주석을 활용했습니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'정류장': ['A', 'B', 'C', 'D', 'E', 'F'], '대기시간': [7, 9, 5, 11, 6, 8]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["정류장"], df["대기시간"],
         color="seagreen", marker="x", linewidth=1.8, markersize=10, label="대기 시간")
plt.annotate("가장 긴 대기", xy=("D", 11), xytext=("C", 12),
             arrowprops=dict(arrowstyle="->"))
plt.title("7. 버스 평균 대기 시간")
plt.xlabel("정류장")
plt.ylabel("대기시간(분)")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
7. 버스 평균 대기 시간
직선 그래프

8. 8. 독서 페이지 수 변화

면적 채우기로 독서량 흐름을 강조합니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'요일': ['월', '화', '수', '목', '금', '토'], '페이지': [20, 35, 30, 45, 60, 72]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["요일"], df["페이지"],
         color="mediumvioletred", marker="o", linewidth=3, label="읽은 페이지")
plt.fill_between(df["요일"], df["페이지"], alpha=0.18)
plt.title("8. 독서 페이지 수 변화")
plt.xlabel("요일")
plt.ylabel("페이지")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
8. 독서 페이지 수 변화
직선 그래프

9. 9. 운동 거리 변화

목표선과 삼각형 마커로 목표 달성 여부를 표현합니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'날짜': ['월', '화', '수', '목', '금', '토'], '거리': [1.2, 2.0, 1.8, 2.5, 3.1, 4.0]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["날짜"], df["거리"],
         color="teal", marker="^", linewidth=3, markersize=8, label="운동 거리")
plt.axhline(3, color="green", linestyle="--", label="목표선 3km")
plt.title("9. 운동 거리 변화")
plt.xlabel("날짜")
plt.ylabel("거리(km)")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
9. 운동 거리 변화
직선 그래프

10. 10. 학급 평균 점수 변화

계단형 선 그래프로 단계적 향상을 표현합니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'단원': ['1단원', '2단원', '3단원', '4단원', '5단원'], '평균점수': [72, 76, 81, 85, 88]})

plt.figure(figsize=(7.4, 4.6))
plt.plot(df["단원"], df["평균점수"],
         color="navy", drawstyle="steps-post", marker="o", linewidth=3, label="평균 점수")
plt.axhline(df["평균점수"].mean(), color="gray", linestyle=":", label="평균선")
plt.title("10. 학급 평균 점수 변화")
plt.xlabel("단원")
plt.ylabel("평균점수")
plt.grid(True, linestyle=":", alpha=0.5)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
10. 학급 평균 점수 변화
막대 그래프

11. 1. 과일 판매량

세로 막대, 서로 다른 색, 테두리, 값 표시, 최고값 주석

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'과일': ['사과', '바나나', '포도', '딸기'], '판매량': [35, 28, 22, 40]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.bar(df["과일"], df["판매량"], color=["#60a5fa", "#34d399", "#fbbf24", "#f87171"], edgecolor="black", linewidth=1.2, label="판매량")
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2,
             height + max(df["판매량"]) * 0.025,
             f"{int(height):,}", ha="center")
plt.annotate("최고 판매", xy=('딸기', 40), xytext=('포도', 44),
             arrowprops=dict(arrowstyle="->"))

plt.title("1. 과일 판매량")
plt.xlabel("과일")
plt.ylabel("판매량")
plt.grid(True, axis="y", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
1. 과일 판매량
막대 그래프

12. 2. 교통수단 이용자 수

가로 막대, 값 라벨, x축 격자

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'교통수단': ['버스', '지하철', '자전거', '도보'], '이용자수': [120, 160, 55, 80]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.barh(df["교통수단"], df["이용자수"], color="#38bdf8", edgecolor="black", alpha=0.86, label="이용자수")
for bar in bars:
    width = bar.get_width()
    plt.text(width + max(df["이용자수"]) * 0.02,
             bar.get_y() + bar.get_height()/2,
             f"{int(width):,}", va="center")

plt.title("2. 교통수단 이용자 수")
plt.xlabel("교통수단")
plt.ylabel("이용자수")
plt.grid(True, axis="x", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
2. 교통수단 이용자 수
막대 그래프

13. 3. 과목별 평균 점수

패턴 막대, 85점 기준선, 값 표시

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'과목': ['국어', '수학', '영어', '과학'], '평균': [82, 88, 79, 91]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.bar(df["과목"], df["평균"], color="#a78bfa", edgecolor="black", hatch="//", label="평균")
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2,
             height + max(df["평균"]) * 0.025,
             f"{int(height):,}", ha="center")
plt.axhline(85, color="red", linestyle="--", label="기준선")

plt.title("3. 과목별 평균 점수")
plt.xlabel("과목")
plt.ylabel("평균")
plt.grid(True, axis="y", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
3. 과목별 평균 점수
막대 그래프

14. 4. 월별 용돈 사용액

원 단위 데이터, 평균선, 점 패턴

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'월': ['3월', '4월', '5월', '6월'], '사용액': [45000, 52000, 48000, 61000]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.bar(df["월"], df["사용액"], color="#fb7185", edgecolor="black", hatch="..", alpha=0.86, label="사용액")
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2,
             height + max(df["사용액"]) * 0.025,
             f"{int(height):,}", ha="center")
plt.axhline(df["사용액"].mean(), color="gray", linestyle=":", label="평균선")

plt.title("4. 월별 용돈 사용액")
plt.xlabel("월")
plt.ylabel("사용액(원)")
plt.grid(True, axis="y", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
4. 월별 용돈 사용액
막대 그래프

15. 5. 동아리 회원 수

좁은 막대 폭, xx 패턴, 값 표시

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'동아리': ['코딩', '축구', '밴드', '과학'], '회원수': [24, 31, 18, 27]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.bar(df["동아리"], df["회원수"], width=0.5, color="#34d399", edgecolor="black", hatch="xx", label="회원수")
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2,
             height + max(df["회원수"]) * 0.025,
             f"{int(height):,}", ha="center")

plt.title("5. 동아리 회원 수")
plt.xlabel("동아리")
plt.ylabel("회원수")
plt.grid(True, axis="y", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
5. 동아리 회원 수
막대 그래프

16. 6. 지역별 미세먼지

주의 기준선, 색상 조합, 주석

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'지역': ['서울', '전주', '부산', '대구'], '미세먼지': [42, 35, 29, 50]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.bar(df["지역"], df["미세먼지"], color=["#facc15", "#86efac", "#93c5fd", "#fb7185"], edgecolor="black", label="미세먼지")
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2,
             height + max(df["미세먼지"]) * 0.025,
             f"{int(height):,}", ha="center")
plt.axhline(40, color="red", linestyle="--", label="기준선")
plt.annotate("주의 필요", xy=('대구', 50), xytext=('부산', 55),
             arrowprops=dict(arrowstyle="->"))

plt.title("6. 지역별 미세먼지")
plt.xlabel("지역")
plt.ylabel("미세먼지(㎍/㎥)")
plt.grid(True, axis="y", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
6. 지역별 미세먼지
막대 그래프

17. 7. 음식별 칼로리

가로 막대, kcal 값 라벨

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'음식': ['김밥', '라면', '샐러드', '비빔밥'], '칼로리': [420, 510, 180, 650]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.barh(df["음식"], df["칼로리"], color="#f97316", edgecolor="black", alpha=0.86, label="칼로리")
for bar in bars:
    width = bar.get_width()
    plt.text(width + max(df["칼로리"]) * 0.02,
             bar.get_y() + bar.get_height()/2,
             f"{int(width):,}", va="center")

plt.title("7. 음식별 칼로리")
plt.xlabel("음식")
plt.ylabel("칼로리(kcal)")
plt.grid(True, axis="x", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
7. 음식별 칼로리
막대 그래프

18. 8. 앱별 사용 시간

사선 패턴, 60분 기준선, 투명도

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'앱': ['유튜브', '카톡', '게임', '검색'], '사용시간': [95, 60, 45, 35]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.bar(df["앱"], df["사용시간"], color="#818cf8", edgecolor="black", hatch="\\", alpha=0.75, label="사용시간")
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2,
             height + max(df["사용시간"]) * 0.025,
             f"{int(height):,}", ha="center")
plt.axhline(60, color="red", linestyle="--", label="기준선")

plt.title("8. 앱별 사용 시간")
plt.xlabel("앱")
plt.ylabel("사용시간(분)")
plt.grid(True, axis="y", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
8. 앱별 사용 시간
막대 그래프

19. 9. 학년별 학생 수

넓은 막대, y축 범위 조절, 값 표시

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'학년': ['1학년', '2학년', '3학년'], '학생수': [125, 118, 130]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.bar(df["학년"], df["학생수"], width=0.8, color="#22c55e", edgecolor="black", hatch="--", label="학생수")
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2,
             height + max(df["학생수"]) * 0.025,
             f"{int(height):,}", ha="center")
plt.ylim(100, 140)

plt.title("9. 학년별 학생 수")
plt.xlabel("학년")
plt.ylabel("학생수")
plt.grid(True, axis="y", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
9. 학년별 학생 수
막대 그래프

20. 10. 쇼핑 품목별 지출 금액

금액 데이터, 최고 지출 주석, 평균선

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'품목': ['문구', '의류', '간식', '도서'], '금액': [15000, 62000, 18000, 32000]})

plt.figure(figsize=(7.4, 4.6))
bars = plt.bar(df["품목"], df["금액"], color="#f472b6", edgecolor="black", hatch="oo", alpha=0.86, label="금액")
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2,
             height + max(df["금액"]) * 0.025,
             f"{int(height):,}", ha="center")
plt.axhline(df["금액"].mean(), color="gray", linestyle=":", label="평균선")
plt.annotate("최고 지출", xy=('의류', 62000), xytext=('간식', 68000),
             arrowprops=dict(arrowstyle="->"))

plt.title("10. 쇼핑 품목별 지출 금액")
plt.xlabel("품목")
plt.ylabel("금액(원)")
plt.grid(True, axis="y", linestyle="--", alpha=0.4)
plt.legend()
plt.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
10. 쇼핑 품목별 지출 금액
이중 y축 혼합 그래프

21. 1. 월별 매출과 광고비

왼쪽 y축은 막대 매출, 오른쪽 y축은 직선 광고비입니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'월': ['1월', '2월', '3월', '4월', '5월', '6월'], '매출': [120, 135, 128, 150, 170, 190], '광고비': [20, 25, 22, 30, 35, 40]})

fig, ax1 = plt.subplots(figsize=(7.4, 4.6))

# 왼쪽 y축: 막대그래프
bars = ax1.bar(df["월"], df["매출"],
               color="#93c5fd", edgecolor="black",
               alpha=0.85, label="매출(만원)")
ax1.set_xlabel("월")
ax1.set_ylabel("매출(만원)", color="royalblue")
ax1.tick_params(axis="y", labelcolor="royalblue")
ax1.grid(True, axis="y", linestyle="--", alpha=0.35)

for bar in bars:
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2,
             height + max(df["매출"]) * 0.02,
             f"{height:g}", ha="center", fontsize=9)

# 오른쪽 y축: 직선그래프
ax2 = ax1.twinx()
ax2.plot(df["월"], df["광고비"],
         color="crimson", marker="o",
         linewidth=3, markersize=7,
         label="광고비(만원)")
ax2.set_ylabel("광고비(만원)", color="crimson")
ax2.tick_params(axis="y", labelcolor="crimson")

plt.title("1. 월별 매출과 광고비")

# 두 축의 범례 합치기
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc="upper left")

fig.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
1. 월별 매출과 광고비
이중 y축 혼합 그래프

22. 2. 주간 공부 시간과 집중도

왼쪽 y축은 막대 공부시간, 오른쪽 y축은 직선 집중도입니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'요일': ['월', '화', '수', '목', '금', '토', '일'], '공부시간': [2, 3, 2.5, 4, 3.5, 5, 4.5], '집중도': [65, 70, 68, 78, 75, 85, 82]})

fig, ax1 = plt.subplots(figsize=(7.4, 4.6))

# 왼쪽 y축: 막대그래프
bars = ax1.bar(df["요일"], df["공부시간"],
               color="#93c5fd", edgecolor="black",
               alpha=0.85, label="공부시간")
ax1.set_xlabel("요일")
ax1.set_ylabel("공부시간", color="royalblue")
ax1.tick_params(axis="y", labelcolor="royalblue")
ax1.grid(True, axis="y", linestyle="--", alpha=0.35)

for bar in bars:
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2,
             height + max(df["공부시간"]) * 0.02,
             f"{height:g}", ha="center", fontsize=9)

# 오른쪽 y축: 직선그래프
ax2 = ax1.twinx()
ax2.plot(df["요일"], df["집중도"],
         color="crimson", marker="o",
         linewidth=3, markersize=7,
         label="집중도(점)")
ax2.set_ylabel("집중도(점)", color="crimson")
ax2.tick_params(axis="y", labelcolor="crimson")

plt.title("2. 주간 공부 시간과 집중도")

# 두 축의 범례 합치기
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc="upper left")

fig.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
2. 주간 공부 시간과 집중도
이중 y축 혼합 그래프

23. 3. 지역별 강수량과 습도

왼쪽 y축은 막대 강수량, 오른쪽 y축은 직선 습도입니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'지역': ['서울', '전주', '부산', '대구', '광주'], '강수량': [12, 18, 30, 8, 22], '습도': [60, 65, 75, 55, 70]})

fig, ax1 = plt.subplots(figsize=(7.4, 4.6))

# 왼쪽 y축: 막대그래프
bars = ax1.bar(df["지역"], df["강수량"],
               color="#93c5fd", edgecolor="black",
               alpha=0.85, label="강수량(mm)")
ax1.set_xlabel("지역")
ax1.set_ylabel("강수량(mm)", color="royalblue")
ax1.tick_params(axis="y", labelcolor="royalblue")
ax1.grid(True, axis="y", linestyle="--", alpha=0.35)

for bar in bars:
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2,
             height + max(df["강수량"]) * 0.02,
             f"{height:g}", ha="center", fontsize=9)

# 오른쪽 y축: 직선그래프
ax2 = ax1.twinx()
ax2.plot(df["지역"], df["습도"],
         color="crimson", marker="o",
         linewidth=3, markersize=7,
         label="습도(%)")
ax2.set_ylabel("습도(%)", color="crimson")
ax2.tick_params(axis="y", labelcolor="crimson")

plt.title("3. 지역별 강수량과 습도")

# 두 축의 범례 합치기
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc="upper left")

fig.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
3. 지역별 강수량과 습도
이중 y축 혼합 그래프

24. 4. 상품별 판매량과 만족도

왼쪽 y축은 막대 판매량, 오른쪽 y축은 직선 만족도입니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'상품': ['A', 'B', 'C', 'D', 'E'], '판매량': [80, 120, 90, 150, 110], '만족도': [3.8, 4.2, 3.9, 4.7, 4.3]})

fig, ax1 = plt.subplots(figsize=(7.4, 4.6))

# 왼쪽 y축: 막대그래프
bars = ax1.bar(df["상품"], df["판매량"],
               color="#93c5fd", edgecolor="black",
               alpha=0.85, label="판매량(개)")
ax1.set_xlabel("상품")
ax1.set_ylabel("판매량(개)", color="royalblue")
ax1.tick_params(axis="y", labelcolor="royalblue")
ax1.grid(True, axis="y", linestyle="--", alpha=0.35)

for bar in bars:
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2,
             height + max(df["판매량"]) * 0.02,
             f"{height:g}", ha="center", fontsize=9)

# 오른쪽 y축: 직선그래프
ax2 = ax1.twinx()
ax2.plot(df["상품"], df["만족도"],
         color="crimson", marker="o",
         linewidth=3, markersize=7,
         label="만족도(5점)")
ax2.set_ylabel("만족도(5점)", color="crimson")
ax2.tick_params(axis="y", labelcolor="crimson")

plt.title("4. 상품별 판매량과 만족도")

# 두 축의 범례 합치기
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc="upper left")

fig.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
4. 상품별 판매량과 만족도
이중 y축 혼합 그래프

25. 5. 월별 운동 횟수와 체중 변화

왼쪽 y축은 막대 운동횟수, 오른쪽 y축은 직선 체중입니다.

🐍 파이썬 코드
import pandas as pd
import matplotlib.pyplot as plt

# 한글 깨짐 방지 + 마이너스 기호 깨짐 방지
plt.rcParams["font.family"] = "NanumGothic"
plt.rcParams["axes.unicode_minus"] = False

df = pd.DataFrame({'월': ['1월', '2월', '3월', '4월', '5월', '6월'], '운동횟수': [8, 10, 12, 15, 18, 20], '체중': [72, 71.5, 71, 70.2, 69.8, 69.0]})

fig, ax1 = plt.subplots(figsize=(7.4, 4.6))

# 왼쪽 y축: 막대그래프
bars = ax1.bar(df["월"], df["운동횟수"],
               color="#93c5fd", edgecolor="black",
               alpha=0.85, label="운동횟수(회)")
ax1.set_xlabel("월")
ax1.set_ylabel("운동횟수(회)", color="royalblue")
ax1.tick_params(axis="y", labelcolor="royalblue")
ax1.grid(True, axis="y", linestyle="--", alpha=0.35)

for bar in bars:
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2,
             height + max(df["운동횟수"]) * 0.02,
             f"{height:g}", ha="center", fontsize=9)

# 오른쪽 y축: 직선그래프
ax2 = ax1.twinx()
ax2.plot(df["월"], df["체중"],
         color="crimson", marker="o",
         linewidth=3, markersize=7,
         label="체중(kg)")
ax2.set_ylabel("체중(kg)", color="crimson")
ax2.tick_params(axis="y", labelcolor="crimson")

plt.title("5. 월별 운동 횟수와 체중 변화")

# 두 축의 범례 합치기
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc="upper left")

fig.tight_layout()
plt.show()
🖼️ 코드가 출력한 실제 그래프
5. 월별 운동 횟수와 체중 변화