Matplotlib이란?
plot()
import matplotlib.pyplot as plt
# 데이터 생성
x = [1,2,3,4,5]
y = [2,4,6,8,10]
# 선 그래프 그리기
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Example Plot')
# 그래프 출력
plt.show()
plot() 활용pandas의 plot() 메서드는 DataFrame 객체에서 데이터를 시각화 하는데 사용
예를 들어, 선 그래프를 그리기 위해서는 plot() 메서드를 호출하고 x 와 y 인수에 각각 x축과 y축에 해당하는 열을 지정
import pandas as pd
import matplotlib.pyplot as plt
# 샘플 데이터프레임 생성
data = {
'A': [1,2,3,4,5]
'B': [5,4,3,2,1]
}
df = pd.DataFrame(data)
# 선 그래프 그리기
df.plot(x='A', y='B')
plt.show()
plot() 메서드 호출 시 다양한 스타일 옵션을 사용하여 그래프 스타일 설정 가능
color , linestyle , marker 등의 파라미터를 사용하여 선의 색상, 스타일, 마커 변경 가능
ax = df.plot(x='A', y='B', color='green', linestyle='--', marker ='o')
plt.show()
color (색상)
linestyle (선 스타일)
'-' : 실선'--' : 대시선':' : 점선'-.' : 점-대시선marker (마커 - 데이터 포인트를 니타내는 기호)
'o' : 원'^' : 삼각형's' : 사각형'+' : 플러스'x' : 엑스#1 범례 추가 - label 사용
ax = df.plot(x='A', y='B', color='green', linestyle='--', marker='o', label='Data Series')
#2 범례 추가 - legend() 사용
ax.legend(['Data Series'])
set_xlabel() : x축 레이블 명칭 추가set_ylabel() : y축 레이블 명칭 추가set_title() : 그래프 제목 추가ax.set_xlabel('X-axis Label')
ax.set_ylabel('Y-axis Label')
ax.set_title('Title of the Plot')
text() : 그래프의 특정 위치에 텍스트 추가ex.text(3, 3, 'Some Text', fontsize=12)
plot() 함수에 color, linestyle, marker, label 등의 파라미터로 스타일과 범례 적용xlabel(), ylabel(), title(), legend(), text() 함수들을 사용하여 각각의 설정 추가
plot() 함수 자체에는 범례, 제목, 텍스트를 직접적으로 입력하는 기능 Ximport matplotlib.pyplot as plt
# 데이터 생성
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# 그래프 그리기
plt.plot(x, y, color='green', linestyle='--', marker='o', label='Data Series')
# 추가 설정
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Title of the Plot')
plt.legend()
plt.text(3, 8, 'Some Text', fontsize=12) # 특정 좌표에 텍스트 추가
# 그래프 출력
plt.show()
plt.figure() 함수를 사용하여 Figure 객체 생성
→ 이후 figsize 매개변수를 이용하여 원하는 크기로 설정
figsize : 그래프의 가로와 세로 크기를 인치 단위로 설정import matplotlib.pyplot as plt
# Figure 객체 생성 및 사이즈 설정
plt.figure(figsize=(8, 6)) # 가로 8인치, 세로 6인치
# 데이터 생성
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# 그래프 그리기
plt.plot(x, y)
# 그래프 출력
plt.show()
Line Plot (선 그래프)
import seaborn as sns
# 샘플 데이터 load
data = sns.load_dataset('flights')
# 샘플 데이터 그룹화
data_grouped = data[['year', 'passengers']].groupby('year').sum().reset_index()
data_grouped
# 그룹된 데이터 시각화
plt.plot(data_grouped['year'], data_grouped['passengers'])
plt.xlabel('year')
plt.ylabel('passengers')