안녕하세요 :)
seaborn으로 데이터시각화하기 첫번째 게시물은 graph 나열로 시작합니다!
향후 그래프 하나하나의 사용법에 대하여 더 자세히 알아보도록 할게요~*
궁금한점이나 문의사항은 댓글로 남겨주세요!
Chapter1. Python seaborn(sns)으로 만들 수 있는 그래프의 종류¶
seaborn 은 matplotlib와 함께 가장 기본적이고 강력한 시각화 툴로 손꼽힌다.¶
- seaborn은 문법이 더 쉽고 통계 시각화에 다양성을 가짐.
- seaborn은 여러 그림을 한번에 나타내어 편하지만 때문에 메모리를 많이 쓸 수 있음.
- matplotlib은 파이썬 전체적으로 사용가능하다면 seaborn은 pandas와 함께 사용하기에 더 직관적으로 특화되어있음.
- seaborn은 초보자가 사용하기 좋은 옵션으로 자동 세팅됨.
In [1]:
# 기본 라이브러리 설치
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
print('seaborn version: ',sns.__version__)
# 기본 데이터셋 불러오기(seaborn에서 기본 제공하는 데이터셋)
tips = sns.load_dataset('tips')
tips.head()
Out[1]:
기본 그래프의 틀¶
In [2]:
# sns.~plot(data=tips, x=~, y=~) 형태
sns.barplot(data=tips, x='sex', y='tip')
Out[2]:
In [3]:
# sns.~plot(data=tips, x=~, y=~, hue=~) 형태 : 'hue' 옵션에 categorical variable(범주형변수)를 넣어 나눠 표현함
sns.barplot(data=tips, x='sex', y='tip',hue='smoker')
Out[3]:
여러개의 그래프를 한번에 (Subplots)¶
In [4]:
# 기본 데이터셋 불러오기(seaborn에서 기본 제공하는 데이터셋)
titanic = sns.load_dataset('titanic')
titanic.head()
Out[4]:
In [5]:
# 3개의 그래프를 한번에 띄워보자 -> 1행 3열의 형태로 ax도 배열해야!
figure, (ax1, ax2, ax3)=plt.subplots(nrows=1, ncols=3)
# 크기는 subplot갯수에 맞게 조절
figure.set_size_inches(18,8)
# 'ax' 옵션을 주지 않는다면 오른쪽(ax3)부터 채워지게 된다.
sns.countplot(data=titanic, x='pclass', hue='survived', ax=ax1)
sns.countplot(data=titanic, x='sex', hue='survived', ax=ax2)
sns.countplot(data=titanic, x='embarked', hue='survived', ax=ax3)
Out[5]:
In [6]:
# 5개의 그래프를 한번에 띄워보자 -> 2행 3열의 형태로 ax도 배열해야!
figure, ((ax1, ax2, ax3), (ax4, ax5, ax6))=plt.subplots(nrows=2, ncols=3)
# 크기는 subplot갯수에 맞게 조절
figure.set_size_inches(18,8)
# 'ax' 옵션을 주지 않는다면 오른쪽(ax3)부터 채워지게 된다.
sns.countplot(data=titanic, x='pclass', hue='survived', ax=ax1)
sns.countplot(data=titanic, x='sex', hue='survived', ax=ax2)
sns.countplot(data=titanic, x='embarked', hue='survived', ax=ax3)
sns.countplot(data=titanic, x='sibsp', hue='survived', ax=ax4)
sns.countplot(data=titanic, x='parch', hue='survived', ax=ax5)
Out[6]:
seaborn 의 API 소개¶
1. Relational plots¶
- relplot하나로 scatterplot 및 lineplot 커버 가능
1) scatterplot¶
- Draw a scatter plot with possibility of several semantic groupings.
In [7]:
sns.scatterplot(data=tips, x="total_bill", y="tip")
Out[7]:
2) lineplot¶
- Draw a line plot with possibility of several semantic groupings.
In [8]:
flights = sns.load_dataset("flights")
sns.lineplot(data=flights, x="year", y="passengers")
Out[8]:
2. Distribution plots¶
- displot하나로도 histplot, kdeplot, ecdfplot, rugplot 커버 가능
- 향후 distplot은 displot과 histplot으로 대체될 예정
1) histplot¶
- Plot univariate or bivariate histograms to show distributions of datasets.
In [9]:
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="flipper_length_mm")
Out[9]:
2) kdeplot¶
- Plot univariate or bivariate distributions using kernel density estimation.
In [10]:
sns.kdeplot(data=tips, x="total_bill")
Out[10]:
3) ecdfplot¶
- Plot empirical cumulative distribution functions.
In [11]:
sns.ecdfplot(data=penguins, x="flipper_length_mm")
Out[11]:
4) rugplot¶
- Plot marginal distributions by drawing ticks along the x and y axes.
In [12]:
sns.rugplot(data=tips, x="total_bill")
Out[12]:
3. Categorical plots¶
- catplot하나로도 커버 가능
1) countplot¶
- Show the counts of observations in each categorical bin using bars.
In [13]:
titanic = sns.load_dataset("titanic")
sns.countplot(x="class", data=titanic)
Out[13]:
2) barplot¶
- Show point estimates and confidence intervals as rectangular bars.
In [14]:
sns.barplot(x="day", y="total_bill", data=tips)
Out[14]:
3) boxplot¶
- Draw a box plot to show distributions with respect to categories.
In [15]:
sns.boxplot(x=tips["total_bill"])
Out[15]:
4) violinplot¶
- Draw a combination of boxplot and kernel density estimate.
In [16]:
sns.violinplot(x=tips["total_bill"])
Out[16]:
5) swarmplot¶
- Draw a categorical scatterplot with non-overlapping points.
- stripplot은 데이터 포인트가 중복되어 범주별 분포를 그리는 반면, swarmplot은 데이터의 분산까지 고려하여 데이터 포인트가 서로 중복되지 않도록 그림.
- 데이터가 퍼져 있는 정도를 입체적으로 볼 수 있다.
In [17]:
sns.swarmplot(x=tips["total_bill"])
Out[17]:
3. Regression plots¶
1) lmplot¶
- Plot data and regression model fits across a FacetGrid.
In [18]:
sns.lmplot(x="total_bill", y="tip", data=tips)
Out[18]:
2) displot¶
- Plot data and a linear regression model fit.
- The regplot() and lmplot() functions are closely related, but the former is an axes-level function while the latter is a figure-level function that combines regplot() and FacetGrid.
In [19]:
sns.regplot(x="total_bill", y="tip", data=tips, lowess=True)
Out[19]:
3) residplot¶
- Plot the residuals of a linear regression.
In [20]:
iris = sns.load_dataset("iris")
sns.residplot(x="petal_length", y="petal_width", data=iris, lowess=True)
Out[20]:
4. Matrix plots¶
1) heatmap¶
- Plot rectangular data as a color-encoded matrix.
In [21]:
flights = sns.load_dataset("flights").pivot("month", "year", "passengers")
sns.heatmap(flights)
Out[21]:
2) clustermap¶
- Plot a matrix dataset as a hierarchically-clustered heatmap.
In [22]:
a=iris.head(20)
a.pop("species")
sns.clustermap(a)
Out[22]:
5. Multi-plot grids¶
1) pairplot¶
- Plot pairwise relationships in a dataset.
In [23]:
sns.pairplot(penguins)
Out[23]:
2) jointplot¶
- Draw a plot of two variables with bivariate and univariate graphs.
In [24]:
sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm")
Out[24]:
'Data visualization with python' 카테고리의 다른 글
| [Python] matplotlib pyplot - barplot with annotation (0) | 2021.03.05 |
|---|---|
| [Python] seaborn - sns.relplot (lineplot, scatterplot 한방에 해결) (0) | 2021.01.26 |