컴붕이의 감자 탈출기/혼공분석

[혼공분석] 5주차_데이터 시각화하기

potato2brain 2025. 2. 6. 00:28

05 - 1 맷플롯립 기본 요소 알아보기

Figure 객체

  • 모든 그래프 구성 요소를 담고 있는 최상위 객체
  • 명시적으로 figure 객체를 만들어 활용하면 다양한 그래프 옵션 조절 가능

그래프 크기 바꾸기

  • figsize 매개변수
plt.figure(figsize=(9,6)) #너비가 9인치, 높이가 6인치인 피겨 객체 생성
plt.scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
plt.show()
  • dpi 매개변수
plt.figure(dpi=144)
plt.scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
plt.show()

❗️DPI란? dot per inch의 약자로 1인치를 몇 개의 점으로 표현하는지 나타낸다. 맷플롯립의 기본 DPI는 72로 설정 돼 있음

 

 

reParams 객체

  • 맷플롯립 그래프의 기본값을 관리하는 객체
  • 이후에 그려지는 모든 그래프에 바뀐 설정이 적용됨
  • DPI 기본값 바꾸기
plt.rcParams['figure.dpi'] = 100
  • 산점도 마커 모양 바꾸기
plt.rcParams['scatter.marker'] = '*' #기존에 o였던 마커가 +로 나타남

 

 

여러개의 서브플롯 출력하기

  • subplots()함수에 원하는 서브플롯 개수를 지정
  • 매개변수 첫번째로 행, 두번째로 열 이들어감
fig, axs = plt.subplots(1,2,figsize=(10,4))

axs[0].scatter(ns_book7['도서권수'],ns_book7['대출건수'],alpha = 0.1)
axs[0].set_title('scatter plot')
axs[0].set_xlabel('number of books')
axs[0].set_ylabel('borrow count')

axs[1].hist(ns_book7['대출건수'], bins=100)
axs[1].set_title('histogram')
axs[1].set_yscale('log')
axs[1].set_xlabel('borrow count')
axs[1].set_ylabel('frequency')

 

 

05 - 2 선 그래프와 막대 그래프 그리기

선 그래프 그리기

선 모양과 색상 바꾸기

  • linestyle= 매개변수로 선 모양 지정 가능 (실선 : '-' , 점선 : ':' , 쇄선 : '-.' , 파선 : '--')
  • color = 매개변수로 색상 지정
  • marker 매개변수 사용 가능
plt.plot(count_by_year,marker = '*', linestyle = ':', color = 'red')
plt.title('books by year')
plt.xlabel('year')
plt.ylabel('number of books')
plt.show()

 

선 그래프 눈금 개수 조절 및 마커에 텍스트 표시하기

  • xticks() 함수로 x축 눈금 지정
  • yticks() 함수로 y축 눈금 지정
  • annotate()함수로 그래프에 값을 표시
  • xytext, textcoords 매개변수를 통해 마커위치 조정가능
plt.plot(count_by_year,marker = '*', linestyle = '-', color = 'green')
plt.title('books by year')
plt.xlabel('year')
plt.ylabel('number of books')
plt.xticks(range(1947, 2030, 10))
for idx, val in count_by_year[::5].items():
    plt.annotate(val, (idx, val), xytext=(2,2), textcoords='offset points')
plt.show()

 

막대 그래프 그리기

텍스트 정렬, 막대 조절 및 색상 바꾸기

plt.bar(count_by_subject.index, count_by_subject.values)
plt.title('Books by subject')
plt.xlabel('subject')
plt.ylabel('number of books')
for idx, val in count_by_subject.items():
    plt.annotate(val, (idx,val), xytext=(0,2), textcoords='offset points')
plt.show()

과제 입니당

 

 

  • ha 매개변수로 텍스트 정렬. 디폴트 값이 'right'임 
  • fontsize 매개변수로 크기 줄이기
  • width 매개변수로 막대 크기 조절, 기본값은 0.8
plt.bar(count_by_subject.index, count_by_subject.values, width=0.7, color='blue')
plt.title('Books by subject')
plt.xlabel('subject')
plt.ylabel('number of books')
for idx, val in count_by_subject.items():
    plt.annotate(val, (idx,val), xytext=(0,2), textcoords='offset points', fontsize=8, ha='center', color='green')
plt.show()

추가과제 입니당

 

 

 

가로 막대 그래프 그리기

  • barh() 함수
  • 두께를 나타내는 매개변수는 width 가 아닌 height매개변수
  • x축과 y축 값을 모두 바꿔줘야함
plt.barh(count_by_subject.index, count_by_subject.values, height=0.7, color='blue')
plt.title('Books by subject')
plt.xlabel('number of books')
plt.ylabel('subject')
for idx, val in count_by_subject.items():
    plt.annotate(val, (val, idx), xytext=(2,0), textcoords='offset points', fontsize=8, va='center', color='green')
plt.show()