한 연속변수의 분포 :: Python 시각화 기초 - mindscale
Skip to content

한 연속변수의 분포

시본을 이용하여 한 연속변수의 분포를 시각화는 방법을 알아보겠습니다.

import seaborn as sns

시본에는 몇 가지 예제 데이터가 내장되어 있습니다. 팁 데이터를 사용해보겠습니다. 데이터는 pandasDataFrame 형식으로 되어 있습니다.

df = sns.load_dataset('tips')
df.head()
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

히스토그램과 밀도 추정

distplot 함수는 한 연속변수의 분포를 히스토그램과 커널 밀도 추정으로 나타내줍니다. 아래는 팁 액수(tip)의 분포입니다.

sns.distplot(df['tip'])
<matplotlib.axes._subplots.AxesSubplot at 0x176267c2080>

위의 그래프에서 분포는 히스토그램(histogram)과 커널 밀도 추정(kernel density estimation), 두 가지 방식으로 표시되어 있습니다.

히스토그램은 데이터를 구간으로 나누어, 각 구간의 막대그래프를 그린 것입니다. 커널 밀도 추정은 일단 제외하고 히스토그램만 그려보도록 하겠습니다.ㅎ

sns.distplot(df['tip'], kde=False)
<matplotlib.axes._subplots.AxesSubplot at 0x17626823e10>

커널 밀도 추정은 데이터에서 어디가 밀도가 높고 낮은지를 추정하여 그린 것입니다. 간단히 생각하면 히스토그램을 매끄럽게 그린 것이라고 볼 수 있습니다. 아래는 히스토그램 대신 커널 밀도 추정만 그린 것입니다.

sns.distplot(df['tip'], hist=False)
<matplotlib.axes._subplots.AxesSubplot at 0x176268e60f0>

bins로 히스토그램에서 구간의 경계를 지정할 수 있습니다. 커널 밀도 추정은 영향을 받지 않습니다.

sns.distplot(df['tip'], bins=[0, 2, 4, 6, 8, 10])
<matplotlib.axes._subplots.AxesSubplot at 0x17626949550>

rug=True를 하면 실제 데이터가 관찰된 위치를 표시합니다.

sns.distplot(df['tip'], rug=True)
<matplotlib.axes._subplots.AxesSubplot at 0x17626a4ea20>

hist=False: 히스토그램 지움

그래프를 가로로 눕혀서 그릴 수도 있습니다.

sns.distplot(df['tip'], vertical=True)
<matplotlib.axes._subplots.AxesSubplot at 0x17626a85470>

색상을 지정하려면 color를 사용합니다.

sns.distplot(df['tip'], color='green')
<matplotlib.axes._subplots.AxesSubplot at 0x17626c37978>

색상 코드를 사용할 수도 있습니다. 색상코드는 빛의 삼원색인 빨강, 초록, 파랑을 각각 16진수 두 자리로 나타낸 것입니다. 아래는 빨강 B5, 초록 36, 파랑 91을 섞은 색으로 그래프를 그립니다.

sns.distplot(df['tip'], color='#B53691')
<matplotlib.axes._subplots.AxesSubplot at 0x17626d3aa90>

커널 밀도 추정과 히스토그램의 색깔을 각각 지정할 수도 있습니다. 아래는 커널 밀도 추정의 색은 빨강(red), 선의 굵기는 3("lw": 3), 그리고 히스토그램은 노란색(yellow)으로 그립니다.

sns.distplot(
    df['tip'],
    kde_kws={"color": "red", "lw": 3},
    hist_kws={"color": "yellow"})
<matplotlib.axes._subplots.AxesSubplot at 0x17627098c50>