본문 바로가기
Study/2023 GDSC 혼자 공부하는 데이터 분석 with Python

6. 복잡한 데이터 표현하기

by JejuSudal 2023. 6. 5.

6-1. 객체지향 API로 그래프 그리기

화려한 그래프 만들기

pyplot 방식

완벽하게 규칙을 가지고 있지는 않지만, 대체로 이 형식을 따름.

plt.plot([1, 4, 9, 16])
plt.title('simple line graph')
plt.show()

객체지향 API 방식

fig, ax = plt.subplots()
ax.plot([1, 4, 9, 16])
ax.set_title('simple line graph')
fig.show()

발행년도 vs 출판사 산점도 그리기

fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(ns_book8['발행년도'], ns_books['출판사'])
ax.set_title('출판사별 발행도서')
fig.show()

마커 크기 키우기

fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(ns_book8['발행년도'], ns_books['출판사'], s=ns_book8['대출건수'])
ax.set_title('출판사별 발행도서')
fig.show()

대출 빈도에 따라 마커의 크기를 다르게 하기

마커 꾸미기

fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(ns_book8['발행년도'], ns_books['출판사'], 
            linewidths=0.5, edgecolors='k', alpha='0.3',  # 마커 테두리 두께, 테두리 블랙, 투명도
            s=ns_book8['대출건수']*2, c=ns_book8['대출건수'])  # c = 빈도가 크면 색이 달라짐
ax.set_title('출판사별 발행도서')
fig.show()

컬러맵 추가하기

fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(ns_book8['발행년도'], ns_books['출판사'], 
            linewidths=0.5, edgecolors='k', alpha='0.3',  # 마커 테두리 두께, 테두리 블랙, 투명도
            s=ns_book8['대출건수']**1.3, c=ns_book8['대출건수'], cmap='jet')  # 색 (빨강~파랑) 순서로 빈도를 표시
ax.set_title('출판사별 발행도서')
fig.colorbar(sc)
fig.show()

6-2. 맷플롯립의 고급 기능 배우기

그래프를 따로 그리지 않고 하나에 합쳐보자!

여러 개의 선 그래프

여러 번 호출하기, (색은 미리지정된 10개의 색을 사용)

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(line1['발생년도'], line1['대출건수'])
ax.plot(line2['발생년도'], line2['대출건수'])
ax.set_title('년도별 대출건수')
fig.show()

범례 출력하기

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(line1['발생년도'], line1['대출건수'], label='황금가지')
ax.plot(line2['발생년도'], line2['대출건수'], label='비룡소')
ax.set_title('년도별 대출건수')
ax.legend()
fig.show()

x 축 범위 지정하기

fig, ax = plt.subplots(figsize=(8, 6))
for pub in top30_pubs.index[:5]:
	line = ns_book9[ns_book9['출판사'] == pub]
    ax.plot(line['발생년도'], line['대출건수'], label=pub)
ax.set_title('년도별 대출건수')
ax.legend()
ax.set_xlim(1985, 2025)
fig.show()

스택 영역 그래프 그리기

fig, ax = plt.subplots(figsize=(8, 6))  # 그래프 그릴때 NON값을 처리해주기
ax.stackplot(year_cols, ns_book10.loc[top10_pubs].fillna(0), labels=top10_pubs)
ax.set_title('년도별 대출건수')
ax.legend(loc='upper left')
ax.set_xlim(1985, 2025)
fig.show()

여러 개의 막대 그래프 그리기

막대 그래프의 경우 위의 특성의 수치가 더 클 경우, 겹치게 되면 안되므로, 나란히 그래프를 그리는 방법을 선택한다.

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(line1['발생년도']-0.2, line1['대출건수'], width=0.4, label='황금가지')
ax.plot(line2['발생년도']+0.2, line2['대출건수'], width=0.4, label='비룡소')
ax.set_title('년도별 대출건수')
ax.legend()
fig.show()

스택 막대 그래프 (위로 쌓기)

주의할 점: 덮어쓰지 않도록

height1 = [5, 4, 7, 9, 8]
height2 = [3, 2, 4, 1, 2]

plt.bar(range(5), height1, width=0.5)
plt.bar(range(5), height2, bottom=height1, width=0.5)
plt.show()

cumsum() 함수 사용하기

ns_book12 = ns_book10.loc[top10_pubs].cumsum()  # 누적 수치

fig, ax = plt.subplots(figsize=(8, 6))
for i in reversed(range(len(ns_book12))):  # 가장 큰 거부터
	bar = ns_book12.iloc[i]
    label = ns_book12.index[i]
    ax.bar(year_cols, bar, label=label)
ax.set_title('년도별 대출건수')
ax.legend(loc='upper left')
ax.set_xlim(1985, 2025)
fig.show()

원 그래프 그리기

부채꼴의 넒이를 비교할 수는 없음. 두개의 그룹을 비교하는데에는 유용.

fig, ax = plt.subplots(figsize(8, 6))
ax.pie(data, labels=labels)
ax.set_title('출판사 도서비율')
fig.show()

# 비율 표시와 부채꼴 강조하기
fig, ax = plt.subplots(figsize(8, 6))  # 파이썬 문자열 포맷 사용가능 
ax.pie(data, labels=labels, startangle=90, autopct='%.1f%%', explode=[0.1]+[0]*9)
ax.set_title('출판사 도서비율')
fig.show()

모두 합치기

 

728x90

'Study > 2023 GDSC 혼자 공부하는 데이터 분석 with Python' 카테고리의 다른 글

5. 데이터 시각화하기  (0) 2023.06.05
4. 데이터 요약하기  (2) 2023.06.05
3. 데이터 정제하기  (0) 2023.06.05
2. 데이터 수집하기  (3) 2023.06.05
1. 데이터 분석이란?  (0) 2023.06.05