Pandas 시각화
1. 판다스 시각화
Pandas는 DataFrame이나 Series 객체에서 직접 plot() 메서드를 호출하여 다양한 유형의 그래프를 쉽게 생성할 수 있습니다. DataFrame의 컬럼명을 자동으로 레이블로 사용하여 편리합니다. Matplotlib을 기반으로 하여 유연성이 높고, 특히 시계열 데이터 시각화에 강점이 있습니다.
Matplotlib은 뒤에 챕터에 있으므로 여기서는 상세한 옵션값보다는 Pandas의 plot() 메서드를 사용하여 간단한 시각화를 수행하는 방법을 살펴보겠습니다.
그래프는 plt.show()로 출력합니다. 이 교재 화면에서는 실행 블록 아래 결과 칸에 그래프가 그려지며, 코랩에서도 같은 코드로 실행할 수 있습니다.
1.1 기본 선 그래프 그리기
먼저 간단한 선 그래프를 그려보겠습니다. 이 예제에서는 월별 커피 판매량 데이터를 시각화합니다.
import pandas as pd
import matplotlib.pyplot as plt
# 데이터 생성
data = {'month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
'sales': [100, 120, 140, 130, 150, 170]}
df = pd.DataFrame(data)
# 그래프 그리기
# 그래프의 크기를 설정
plt.figure(figsize=(10, 6))
# 선 그래프 그리기
plt.plot(df['month'], df['sales'], marker='o')
# 제목과 축 레이블 추가
plt.title('Monthly Coffee Sales')
# x축과 y축 레이블 추가
plt.xlabel('Month')
plt.ylabel('Sales')
# 격자 추가
plt.grid(True)
plt.show()
위 코드는 월별 커피 판매량 데이터를 시각화하는 선 그래프를 그리는 예제입니다. 뒤에서 배울 matplotlib의 기본적인 사용법을 살펴보았습니다. 다른 라이브러리와도 호환이 잘 된다는 것을 알 수 있습니다.
1.2 Pandas를 이용한 선 그래프 그리기
Pandas의 DataFrame 객체는 plot() 메서드를 제공합니다. 이를 사용하면 Matplotlib을 직접 사용하지 않고도 간단하게 그래프를 그릴 수 있습니다. 위의 예제를 Pandas를 사용하여 다시 작성해보겠습니다.
import pandas as pd
import matplotlib.pyplot as plt
# 데이터 생성
data = {'month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
'sales': [100, 120, 140, 130, 150, 170]}
df = pd.DataFrame(data)
# 선 그래프 그리기
ax = df.plot(x='month', y='sales', marker='o',
title='Monthly Coffee Sales', grid=True, figsize=(10, 6))
plt.show()
2. 다양한 그래프 유형
2.1 막대 그래프(Bar Plot)
막대 그래프(Bar Plot)는 범주형 데이터의 값을 비교할 때 유용합니다. kind='bar'를 사용하여 생성합니다.
import pandas as pd
import matplotlib.pyplot as plt
# 데이터 생성
data = {'Coffee': ['Espresso', 'Latte', 'Cappuccino', 'Americano', 'Mocha'],
'Sales': [150, 200, 180, 220, 130]}
df = pd.DataFrame(data)
# 막대 그래프 그리기
ax = df.plot(x='Coffee', y='Sales', kind='bar',
figsize=(10, 6), title='Coffee Sales by Type')
plt.xlabel('Coffee Type')
# x축 레이블을 45도 회전
plt.xticks(rotation=45)
plt.ylabel('Sales')
plt.show()
2.2 히스토그램(Histogram)
히스토그램(Histogram)은 연속형 데이터의 분포를 보여줍니다. kind='hist'를 사용하여 생성합니다.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 데이터 생성 (100번의 주사위 던지기)
np.random.seed(0)
data = np.random.randint(1, 7, 100)
df = pd.DataFrame(data, columns=['Dice'])
# 히스토그램 그리기
ax = df.plot(kind='hist', bins=6, rwidth=0.5, color='skyblue',
alpha=0.7, figsize=(10, 6), title='Dice Roll Histogram')
plt.show()
2.3 산점도(Scatter Plot)
산점도(Scatter Plot)는 두 변수 간의 관계를 시각화할 때 사용합니다. kind='scatter'를 사용하여 생성합니다.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 데이터 생성
np.random.seed(0)
price = np.random.uniform(3, 7, 50)
# 가격이 높을수록 판매량 감소: 가격 1달러마다 판매량이 15씩 줄고, 무작위 변동(잡음)을 더함
sales = 220 - 15 * price + np.random.normal(0, 10, 50)
data = {'Price': price, 'Sales': sales}
df = pd.DataFrame(data)
# 산점도 그리기
ax = df.plot(x='Price', y='Sales', kind='scatter', figsize=(10, 6), title='Coffee Price vs Sales')
plt.xlabel('Price ($)')
plt.ylabel('Sales')
plt.show()
점들이 왼쪽 위에서 오른쪽 아래로 늘어서 있습니다. 가격(가로축)이 높은 커피일수록 판매량(세로축)이 낮다는 뜻입니다. 판매량을 가격으로 계산하고 잡음을 조금 더했기 때문에 점이 한 줄로 늘어서지는 않지만 방향은 분명합니다. 두 열의 상관계수를 구해 보면 약 -0.88로, -1에 가까운 강한 음의 상관이 나옵니다.
print(df['Price'].corr(df['Sales']))
2.4 파이 차트(Pie Chart)
파이 차트(Pie Chart)는 전체에서 각 항목이 차지하는 비율을 시각화할 때 사용합니다. kind='pie'를 사용하여 생성합니다.
import pandas as pd
import matplotlib.pyplot as plt
# 데이터 생성
data = {'Coffee': ['Espresso', 'Latte', 'Cappuccino', 'Americano', 'Mocha'],
'Sales': [150, 200, 180, 220, 130]}
df = pd.DataFrame(data)
# 파이 차트 그리기
ax = df.plot(y='Sales', kind='pie', labels=df['Coffee'], autopct='%1.1f%%',
startangle=90, shadow=True, figsize=(10, 6), title='Coffee Sales Distribution')
plt.ylabel('') # y 레이블 제거
plt.show()
Pandas의 plot() 메서드는 내부적으로 Matplotlib을 사용하지만, 사용자가 직접 Matplotlib 코드를 작성할 필요 없이 간단하게 그래프를 생성할 수 있게 해줍니다. 더 자세한 내용은 Matplotlib 챕터에서 다루겠습니다.
마지막 수정