Python/데이터 분석

[python] seaborn 데이터 시각화 라이브러리 활용

비전공생's 2022. 4. 11. 23:37

파이썬의 데이터 시각화 라이브러리인 seaborn을 활용해보자.

 

라이브러리 불러오기 및 설정

import seaborn as sns 
sns.set_style({'font.family':'serif', 'font.serif':['Times New Roman']}) 
sns.set_style('darkgrid')
 

 

Figure 여러개 그리기

figure, ((ax1, ax2, ax3),(ax4, ax5,ax6)) = plt.subplots(nrows=2,ncols=3)
figure.set_size_inches(10,6) sns.barplot(x='pclass', y='survived', hue='sex', data=df, ax=ax1)

sns.barplot(x='pclass', y='survived', hue='sex', data=df, ax=ax1)
sns.barplot(x='sex', y='survived', hue='sex', data=df, ax=ax2)
sns.barplot(x='pclass', y='survived', hue='pclass', data=df, ax=ax3)
sns.barplot(x='embarked', y='survived', hue='embarked', data=df, ax=ax4)
sns.barplot(x='pclass', y='survived', hue='embarked', data=df, ax=ax5)
sns.barplot(x='sibsp', y='survived', hue='pclass', data=df, dodge=False, ax=ax6)
 

 

barplot

: 막대그래프

dodge 설정은, 그래프를 누적해서 출력하는 것

# 누적 출력 --> dodge=False
# 기본적으로는 dodge=True로 되어있으나 False를 넘기면 그래프를 누적해서 출력

sns.barplot(x='sex', y='survived', hue='class', palette='Set2', dodge=False, data=df)
 

 

countplot

: 항목별 갯수를 세어주는 그래프

해당 column을 구성하고 있는 value들을 구분하여 보여줌

sns.countplot(x="class", hue="who", data=df)
 

 

boxplot

: 이산형 변수와 연속형 변수를 함께 사용

이산형 변수: Female, Male 처럼 명확하게 구분되는 값

연속형 변수: 정수, 실수 같이 명확히 셀수 없는 범위의 값

범주형 데이터의 분포를 파악하는데 용이함

한개의 컬럼: 데이터프레임.boxplot(column=['컬럼명'])

여러 개의 연속형 변수: ax=fig.add_subplot ax.boxplot

 

# 타이타닉 생존자 별, 연령의 분포

sns.boxplot(x='alive', y='age', data=df)
 

lmplot

: 산점도 그래프로, Linear model plot의 약어

회귀곡선도 그리고, 신뢰구간도 그려줌

단점은 실제 회귀식은 알수는 없음

한꺼번에 성별/pclass별로

요금과 나이의 관계를 보려면 row와 col에 원하는 컬럼명을 넣어주면 됨

 

sns.lmplot(x='fare', y='age', data=df, fit_reg=False, row='sex', col='pclass', height=3)
 

 

 

sns.lmplot(x='sepal_length', y='sepal_width', hue= 'species', data=iris)
 

 

 

pairplot

: 각 column별 데이터에 대한 상관관계나 분류적 특성을 코드 한줄로 확인할 수 있음

데이터 세트의 모든 변수간의 관계를 보여줌

모든 변수의 모든 조합을 자체적으로 수행하여 변수간의 관계를 보여주는 산점도와 히스토그램을 보여줌

sns.pairplot(iris(data명), hue="species(칼럼)", height=2, markers=["o", "s", "D"])
plt.title("그래프명")
 

 

jointplot

: 이변량 그래프와 단변량 그레프를 동시에 볼 수 있는 그래프

이변량: 두 개의 변수만이 포함되는 통계적 분석. (두 변수간의 독립성이나 관련성을 알아보기 위한 빈도분포 분석이나, 단순상관이나 회귀분석, 그리고 하나의 독립변수와 하나의 종속변수로 이루어지는 평균의 차이검정 등은 이변량분석의 예.)

다변량: 사회현상을 설명할 수 있는 자료의 유형을 연구하기 위해 변수들 사이의 관계를 분석하는 것

kind='kde'이면 커널 밀도 히스토그램

sns.pairplot(iris(data명), hue="species(칼럼)", height=2, markers=["o", "s", "D"])
plt.title("그래프명")
 

 

regplot

: 두 변수를 이용하여 선형 회귀 모형을 만들고, 그래프로 표현

sns.regplot(x='sepal_length', y='sepal_width', data=iris)
sns.regplot(x=iris["sepal_length"], y=iris["petal_length"], color='red')