시각화 라이브러리
matplotlib
pip install matplotlib
pyplot
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y) # 선 그래프 그리기
plt.title("Sample Plot") # 제목 추가
plt.xlabel("X-axis") # X축 레이블
plt.ylabel("Y-axis") # Y축 레이블
plt.show() # 그래프 출력
plt.plot(x, y, label='Data 1')
plt.plot(x, [15, 10, 5, 1], label='Data 2')
plt.legend() # 범례 추가
plt.show()
plt.plot(x, y, color='red', linestyle='--', marker='o')
plt.bar(x, y) # 막대 그래프
plt.scatter(x, y) # 산점도
plt.hist(y) # 히스토그램
x = np.array([1, 2, 3, 4])plt.plot(df['x'], df['y'])입력 "항상 x, y가 필요한지, 허용하는 개수는 어느정도인지"
입력 "선, 색상, 스타일, 마커 사용법 상세하게, 그 외 기능들 있다면 추가 설명"
1. 선
linestyle = " "
color = "blue"#FF5733marker = "o"markersize = 10 또는 ms = 10 Line Width
limewith = 2 또는 lw = 2
Title,, Axis Labels, Grid
plt.title('그래프 제목', fontsize =14. fontweight = 'bold')plt.xlabel('X축 레비블, fontsize=12)plt.grid(Ture)plt.grid(True, color = 'gray', linestyle = '--', linewidth = 0.5)plt.grid(axis = 'x')axis 설정을 하면 그리드 활성화 True가 필요 없음plt.grid(axis = 'both', color='gray', linestyle='--', linewidth=0.5)plt.plot(x, y, label='데이터 1')
plt.plot(x, [10, 15, 20, 25], label='데이터 2')
plt.legend() # 범례 추가
plt.style.use('seaborn')"ggplot": "seaborn""classic": Matplotlib 기본 스타일"fivethirtyeight": FiveThirtyEight 블로그 스타일"dark_background": 어두운 배경 스타일figplt.figure()figsize : 가로, 세로 단위 (인치)dpi: 인치당 점의 수 - 해상도 plt.plot(x, y)
plt.title('Line Plot Example')
plt.show()
plt.scatter(x, y)
plt.title('Scatter Plot Example')
plt.show()
categories = ['A', 'B', 'C']
values = [10, 20, 15]
plt.bar(categories, values)
plt.title('Bar Plot Example')
plt.show()
bin(특정구간)에 속하는 데이터의 수data = np.random.randn(1000) # 정규분포를 따르는 1000개의 랜덤 데이터
plt.hist(data, bins=30, color='skyblue', edgecolor='black')
plt.title('Histogram Example')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
patch_artist=True: 색상 적용이 가능import matplotlib.pyplot as plt
# 데이터 준비
data = {
'1학급': [65, 70, 75, 80, 85, 90, 95],
'2학급': [55, 60, 65, 70, 75, 80],
'3학급': [45, 50, 55, 60, 65, 70, 75, 80]
}
# 상자 그림 그리기
box = plt.boxplot(data.values(), labels=data.keys(), patch_artist=True)
# 색상 지정 (for문 없이)
box['boxes'][0].set_facecolor('lightblue') # 1학급 색상
box['boxes'][1].set_facecolor('lightgreen') # 2학급 색상
box['boxes'][2].set_facecolor('lightcoral') # 3학급 색상
# 그래프 제목과 축 레이블 추가
plt.title("학급별 수학 시험 점수 분포")
plt.xlabel("학급")
plt.ylabel("점수")
# 그래프 보여주기
plt.show()
autopct: 각 조각의 비율을 표시하는 형식%1.1f%% : 소수점 첫째 자리까지 표시%1.1f%%: 백분율 기호(단일 %는 특별한 의미가 있으므로 두 개의 %를 사용)import matplotlib.pyplot as plt
# 데이터 준비
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
# 원 그래프 그리기
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
# 그래프 제목 추가
plt.title("원 그래프")
# 그래프 보여주기
plt.axis('equal') # 원을 유지하기 위해
plt.show()
cmap: 데이터의 값을 색상으로 변환하는 방법을 정의viridis: 파란색에서 노란색으로 변하는 색상 맵 (기본 색상 맵)plasma: 보라색에서 노란색으로 변하는 색상 맵hot: 검정에서 빨강, 노랑, 흰색으로 변하는 색상 맵cool: 파란색에서 핑크색으로 변하는 색상 맵gray: 흑백 색상 맵# 데이터 준비
months = ['1월', '2월', '3월', '4월', '5월', '6월',
'7월', '8월', '9월', '10월', '11월', '12월']
temperatures = [2, 3, 8, 15, 20, 25, 28, 27, 22, 15, 8, 3]
# 데이터 배열로 변환
data = np.array(temperatures).reshape(1, -1) # 1행 12열 배열로 변환
# 히트맵 그리기
plt.imshow(data, cmap='hot', interpolation='nearest')
# 축 레이블 설정
plt.title("월별 평균 기온")
plt.xticks(ticks=np.arange(len(months)), labels=months)
plt.yticks([]) # y축 레이블 제거
# 색상 바 추가
plt.colorbar(label='기온 (°C)')
# 그래프 보여주기
plt.show()