00. 데이터 시각화 라이브러리 Matplotlib
시각화의 기초는 해당 사이트에 들어가 어떤 것들이 있는지 먼저 파악해야한다.
https://matplotlib.org/stable/gallery/index
Examples — Matplotlib 3.10.7 documentation
Examples For an overview of the plotting methods we provide, see Plot types This page contains example plots. Click on any image to see the full image and source code. For longer tutorials, see our tutorials page. You can also find external resources and a
matplotlib.org
이런식으로 다양한 example을 보고 골라 쓸 수 있다
# 맷플롯립 라이브러리 불러오기
import matplotlib.pyplot as plt
관습적으로 plt라고 쓴다!
matplotlib로만 호출하면 기능을 일일이 호출해야해서 코드가 길어져서 하위 모듈 사용을 권장한다.
# 그래프와 범례를 그려보자
import matplotlib.pyplot as plt
# plot() 함수의 label 매개변수에 'Square' 문자열 입력
# x축 y축이 넣어짐
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], label = 'Square')
plt.xlabel('X-Label')
plt.ylabel('Y-Label')
# legend() 함수를 사용해서 그래프에 범례 표시
plt.legend() #이걸 넣어야 범례가 표시됨
plt.show()
# 눈금 설정하기 (plt.xtricks)
- 원본데이터 셋을 건들지 않고 변수명은 그대로 두는데, 의미하는 바는 나의 언어로 쓰고싶을때 사용함
ex. M,W -> 남자/여자로 표현
import matplotlib.pyplot as plt
# x 정의
x = [1, 2, 3]
# years는 x축에 표시할 연도
years = ['2030', '2040', '2050']
# values는 y축에 표시할 값
values = [300, 100, 700]
# 막대 그래프 생성, 색상 설정은 color 매개변수로
plt.bar(x, values, color = ['r', 'g', 'b'])
# x축 눈금에 '2030', '2040', '2050'를 표시
plt.xticks(x,years)
plt.show()
#레이블 추가하기 (plt.text)
잠깐 ! enumerate 이해해보기
- 리스트로 예시 들자면 첫번째 값에는 idx가 2번째 값에는 [idx] 값이 들어간다.
values = [25, 40, 30, 20]
for i, value in enumerate(values):
print(i, value)
# enumerate란 ? => i는 0부터 1씩 +되고(index역할), value라는 변수에는 리스트의 값이 들어감
# 1바퀴 : i = 0, value = 25
# 2바퀴 : i = 1, value = 40
# ...
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 20]
# 막대 그래프 생성
plt.bar(categories, values, color='skyblue')
# 각 막대의 중앙에 텍스트 추가
for i, value in enumerate(values):
plt.text(i, value / 2, str(value), ha='center', va='center', color='black', fontsize=10)
plt.title('Bar Chart with Text Annotations')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
# 타이타닉 데이터셋 그래프로 그려보기
- kaggle 데이터 참고
- 데이터가 다를 수 있지만 본인 실습용으로 보시길
https://www.kaggle.com/datasets/euclidsoft/titianic
titanic
타이타닉 탑승자 명단을 사용하여 타이타닉 데이터 분석 및 생존자 예측
www.kaggle.com
# 판다스 라이브러리 불러오기
import pandas as pd
# 타이타닉 CSV 파일 불러오기
titanic = pd.read_csv('/content/sample_data/titanic.csv'
titanic.head(5) # 함수를 통해 어떤 함수인지 보고
titanic.info() # 열에 대한 요약정보를 확인한다.
- Age, cabin, embarked에 결측치가 있구나 (891행중)
- Age는 굳이 실수일 이유는 없으니 integer로 바꿔볼까 ?
- 이런 생각을 한다
# 성별에 따른 생존자의 수 계산
# titanic에 survived가 1인 애들 중의 성별을 세어줘
survived_counts = titanic[titanic['Survived']==1]['Sex'].value_counts()
survived_counts
#수평막대그래프(barh - bar horizinal)
import matplotlib.pyplot as plt
# 수평 막대 그래프 그리기
bars = plt.barh(survived_counts.index, survived_counts, color=['darkturquoise','salmon'])
plt.title('Survived Counts by Gender on Titanic')
plt.xlabel('Count')
plt.ylabel('Gender')
plt.legend(bars, ['Survived - Female', 'Survived - Male'], loc='upper right')
# 차이 강조를 위해 수평선 추가
plt.axvline(x=survived_counts['male'], color='gray', linestyle='--', linewidth=1)
# 생존자 수 표시
for i, value in enumerate(survived_counts):
plt.text(value + 1, i, str(value), ha='left', va='center')
plt.show()
# 파이차트
import matplotlib.pyplot as plt
# 파이 차트 그리기
plt.figure(figsize=(2, 2)) # 흰 도화지를 그린다
plt.pie(survived_counts, labels=['Not Survived', 'Survived'], colors=['orange', 'gold'],
autopct='%0.1f%%', startangle=90, shadow=True, explode=(0, 0.1))
plt.title('Survival Distribution on the Titanic')
plt.show()
- 그래프를 그리고 나면 ? 반드시 인사이트가 많기 때문에 어떤 인사이트가 있는지 해석을 해야한다.
# 히스토그램
- 나이 결측치를 한번 제거 해보겠다.
# 나이 결측치 처리 후
titanic = titanic.dropna(subset=['Age']) #na값을 drop해버림 (삭제해벌임)
print(titanic.info())
import matplotlib.pyplot as plt
# 히스토그램 그리기
plt.figure(figsize=(10, 6))
plt.hist(titanic['Age'], bins=20, color='seagreen', edgecolor='black')
plt.xlabel('Age')
plt.ylabel('Count')
plt.title('Distribution of Ages on the Titanic')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
# insight : 대부분 나이가 20~40대가 있구나 !
#상관행렬
-데이터 분석에서 아주 중요한 아이다!
모든 분석에서 한번씩 사용해 보기를 권장
import pandas as pd
titanic = pd.read_csv('/content/sample_data/titanic_selena.csv')
# 결측치 처리
titanic = titanic.dropna(subset=['Age','Fare'])
# 상관 행렬 계산 (변수간에 상관관계가 어떤지 보는 것이다. 승객id는 특징이 없으니까 뺐다. )
# 연속형 변수만 상관 행렬을 구해줘. numeric_only
correlation_matrix = titanic.drop('PassengerId',axis=1).corr(numeric_only=True)
correlation_matrix
- 연속형 변수만 되기 때문에, object type은 알아서 생략이 됐다.
GPT를 활용한 해석
| 생존 ↔ Pclass (-0.36) |
객실 등급이 생존 확률에 강한 영향 |
| 생존 ↔ Fare (0.27) |
요금이 높을수록 생존 확률 증가 |
| 생존 ↔ Age (-0.08) |
나이는 생존과 큰 관련 없음 |
| 가족 변수 ↔ 생존 (거의 0) |
가족 규모는 생존과 직접적 연관 적음 |
- '상관관계'는 원인과 결과가 아니다 !!!! '인과관계'가 아니다 !!!
- 상관관계는 함께 변화하는 경향이 있다. 비례/반비례 개념인듯
-> 우연히 변할 수도 있고, 다른 요인 때문일 수도 있음
-> ex. 아이스크림 판매량 -> 익사 사고수 상관관계 있음 (사이에 여름이라는 제 3요인)
-> 즉 아이스크림이 익사사고수를 유발하지는 않음
-> 통계적으로 간단히 확인 가능
- 인과관계는 A가 B의 원인이라는 명확한 관계가 존재
-> 통계적 수치로 판단 불가능하고, 실험이나 추가 분석 필요 (굉장히 어려운일)
- 범주형 변수(성별, 혈액형과 같은 그룹)와 연속형 변수(cm, kg 과 같은 수치)는 다르게 구해야한다
import matplotlib.pyplot as plt
# 히트맵 그리기
plt.matshow(correlation_matrix, cmap='PuRd_r')
plt.colorbar()
# x축과 y축의 눈금 설정
plt.xticks(range(len(correlation_matrix.columns)), correlation_matrix.columns, rotation=45)
plt.yticks(range(len(correlation_matrix.columns)), correlation_matrix.columns)
plt.title('Correlation Heatmap of Titanic')
plt.show()
# 이상치 잡는 박스 플롯 !
- 수염에서 벗어난 동그라미 들을 이상치로 분류하게됨 (1분위, 3분위를 벗어난)
import matplotlib.pyplot as plt
# 승객 등급에 따른 나이의 박스 플롯
plt.boxplot([titanic[titanic['Pclass'] == 1]['Age'],
titanic[titanic['Pclass'] == 2]['Age'],
titanic[titanic['Pclass'] == 3]['Age']],
labels=['1st Class', '2nd Class', '3rd Class'])
plt.title('Box Plot for Age by Pclass')
plt.xlabel('Pclass')
plt.ylabel('Age')
plt.show()
댓글