[Jupyter Notebook] Matplotilb로 데이터 시각화하기
2022. 3. 10. 21:15ㆍ독학으로 취업 문 뿌수기/Jupyter Notebook
728x90
반응형
SMALL
※ 라이브러리 불러오기
import matplotlib.pyplot as plt
※ 필요없는 정보 보여지지 않음
plt.show()
1. 그래프 기본
01. 그래프 기본.html
0.62MB
2. 축
02. 축.html
0.60MB
plt.plot(x,y)
plt.xlabel('X축', color = 'red', loc = 'right') #loc는 로케이션(위치)로 left, center, right 중에서 선택
plt.ylabel('Y축', color = '#00aa00', loc = 'top') #top, center, bottom
3. 범례
03. 범례.html
0.59MB
plt.plot(x,y, label='무슨 데이터')
plt.legend(loc = (0.7, 0.8)) #x축, y축 0~1사이
4. 스타일
04. 스타일.html
0.83MB
plt.plot(x, y, marker = 'o', markersize = 10, markeredgecolor = 'red', markerfacecolor = 'yellow')
plt.plot(x, y, linestyle = '-.')
plt.plot(x, y, 'ro--') #color, marker, linestyle
- 축약어, 투명도
plt.plot(x, y, marker = 'o', mfc='red', ms=10, mec='blue', ls=':', alpha=0.7)
- 그래프 크기, 해상도
plt.figure(figsize=(10, 5), dpi=200) #dpi는 해상도
5. 파일 저장
05. 파일저장.html
0.60MB
plt.figure(dpi=200) #화면에 보여지는 dpi 값
plt.plot(x, y)
plt.savefig('graph_200.png', dpi=100) #파일로 저장되는 dpi 값
6. 텍스트
06. 텍스트.html
0.56MB
- 각 마커마다 숫자 표시( +0.3은 위치 조절) - 꺾은선 그래프의 경우
for idx, txt in enumerate(y):
plt.text(x[idx], y[idx] + 0.3, txt, ha='center', color='blue')
- 막대 그래프의 경우
for idx, rect in enumerate(bar):
plt.text(idx, rect.get_height() + 0.5, values[idx], ha='center', color='blue')
7. 여러 데이터
07. 여러 데이터.html
0.61MB
8. 막대 그래프(기본)
08. 막대 그래프(기본).html
0.59MB
labels = ['강백호', '서태웅', '정대만']
values = [190, 187, 184]
ticks = ['1번학생', '2번학생', '3번학생']
plt.bar(labels, values, width=0.5)
plt.ylim(175, 195) #y축에 제한을 줌)
plt.xticks(labels, ticks, rotation=45)
9. 막대 그래프(심화)
09. 막대 그래프(심화).html
0.56MB
- 가로 막대 그래프
plt.barh(labels, values)
plt.xlim(175,195)
- 각 그래프 무늬 설정
bar = plt.bar(labels, values)
bar[0].set_hatch('/')
bar[1].set_hatch('x')
bar[2].set_hatch('..')
10. DataFrame 활용
10. DataFrame 활용.html
0.61MB
- Pandas 라이브러리 불러오기
import pandas as pd
- 저장된 엑셀 파일 경로 불러오기
df = pd.read_excel('../Pandas/score.xlsx')
plt.plot(df['지원번호'], df['영어'])
plt.plot(df['지원번호'], df['수학'])
plt.grid(axis='x', color='purple', alpha=0.5, linestyle='--', linewidth=2)
df.groupby('학교')
11. 누적 막대 그래프
11. 누적 막대 그래프.html
0.59MB
plt.bar(df['이름'], df['국어'])
plt.bar(df['이름'], df['영어'], bottom=df['국어'])
plt.bar(df['이름'], df['수학'], bottom=df['국어'] + df['영어'])
12. 다중 막대 그래프
12. 다중 막대 그래프.html
0.60MB
- 라이브러리 불러오기
import numpy as np
df.shape[0] #(row 개수, col 개수) [0,1]
N = df.shape[0]
index = np.arange(N)
w = 0.25
plt.bar(index - w, df['국어'], width = w)
plt.bar(index, df['영어'], width = w)
plt.bar(index + w, df['수학'], width = w)
13. 원 그래프(기본)
13. 원그래프(기본).html
0.62MB
values = [30, 25, 20, 13, 10, 2]
labels = ['Python', 'Java', 'Javascript', 'C#', 'C/C++', 'ETC']
plt.pie(values, labels = labels, autopct = '%.1f%%', startangle=90, counterclock=False) #소수 첫째자리 비율 퍼센트, 시계방향으로 배열
- 각 파이별로 띄우기 (0.05만큼이 공간 발생)
explode = [0.05] * 6
plt.pie(values, labels = labels, explode=explode)
plt.legend(loc=(1.2, 0.3)) #location
14. 원 그래프(심화)
14. 원 그래프(심화).html
0.64MB
- explode로 띄우는 것이 아닌 파이 사이 선을 굵게 만들어 각 데이터를 분리해서 보는 효과
wedgeprops = {'width':0.8, 'edgecolor':'w', 'linewidth':5}
plt.pie(values, labels = labels, autopct = '%.1f%%', startangle=90, counterclock=False, colors=colors, wedgeprops=wedgeprops)
- 조건: 10퍼센트 이상인 값은 값 표시, 미만인 값은 빈칸 처리
def custom_autopct(pct):
return ('%.0f%%' % pct) if pct >= 10 else ''
15. 산점도 그래프
15. 산점도 그래프.html
0.61MB
import numpy as np
sizes = np.random.rand(8) * 1000
sizes
sizes = df['학년'] * 500
plt.scatter(df['영어'], df['수학'], s=sizes, c=df['학년'], cmap='viridis', alpha=0.3)
plt.colorbar(ticks=[1,2,3], label='학년', shrink=0.5, orientation='horizontal')
16. 여러 그래프
16. 여러 그래프.html
0.63MB
fig, axs = plt.subplots(2, 2, figsize=(15, 10)) #2x2에 해당하는 plot을 생성
fig.suptitle('여러 그래프 넣기')
#첫 번째 [0, 0]위치
axs[0, 0].bar(df['이름'], df['국어'], label='국어점수') #데이터 설정
axs[0, 0].set_title('첫 번째 그래프') #제목
axs[0, 0].legend() #범례
axs[0, 0].set(xlabel='이름', ylabel='점수') #x, y축 label
axs[0, 0].set_facecolor('lightyellow') #전면 색
axs[0, 0].grid(linestyle='--', linewidth=0.5)
728x90
반응형
LIST
'독학으로 취업 문 뿌수기 > Jupyter Notebook' 카테고리의 다른 글
[Jupyter Notebook] Pandas로 데이터 분석하기 (1) | 2022.02.28 |
---|---|
아나콘다 설치와 주피터 노트북 사용법 (0) | 2022.02.27 |