본문 바로가기

DB엔지니어가 공부하는 python

[python]데이터 시각화 seaborn 라이브러리 실습 해보기 feat.lmplot

##[python]데이터 시각화 seaborn 라이브러리 실습 해보기 feat. lmplot

 

안녕하세요.

 

오늘은 데이터 시각화 라이브러리중 seaborn에 대해서 알아보겠습니다.

 

데이터 시각화에 관심이 있고, 능력이 있으신 분들께서는 이미 많은 분들이 알고 계시는

 

라이브러리인데요,

 

seaborn은 matplotlib을 기반으로 만들어진 라이브러리로 high-level interface를 제공하고 있습니다.

 

matplotlib을 좀 더 사용하기 쉽게 만든 라이브러리로 생각하시면 되겠습니다.

 

먼저, seaborn의 공식 사이트를  소개하겠습니다.

http://seaborn.pydata.org/index.html

 

seaborn: statistical data visualization — seaborn 0.9.0 documentation

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. For a brief introduction to the ideas behind the library, you can read the introductory note

seaborn.pydata.org

여기 들어가 보시면, tutorial, api 등 seaborn과 관련된 정보를 확인하실 수 있습니다.

 

이렇게 다양한 시각화 아웃풋으로 데이터를 확인할 수 있습니다.

 

이중에서도 오늘 제가 실습을 해 볼 시각화 모델은 lmplot, Anscombe's quartet입니다.

 

우선 seaborn 라이브러리 홈페이지에서 상단의 Gallery 메뉴를 선택합니다.

 

그러면 아래와 같은 화면이 뜹니다.

import seaborn as sns
sns.set(style="ticks")

# Load the example dataset for Anscombe's quartet
df = sns.load_dataset("anscombe")

# Show the results of a linear regression within each dataset
sns.lmplot(x="x", y="y", col="dataset", hue="dataset", data=df,
           col_wrap=2, ci=None, palette="muted", height=4,
           scatter_kws={"s": 50, "alpha": 1})

 

seaborn은 이미 데이터셋을 내장하고 있습니다.

 

화면 아래에 있는 소스를 그대로 불러와서 실행하게 되면 위와 같은 그래프를 확인할 수 있습니다.

 

이 그래프를 보면서 무엇을 이해할 수 있느냐가 중요할 것 같은데요.

 

저기 보이는 4개 그래프를 보면 모양이 각기 다릅니다. 하지만 저 데이터 셋의 평균, 표준편차, 상관계수, 회귀 값은

 

동일한 데이터 셋입니다.

 

수치상의 계산은 정확하게 맞아떨어지지만 서로의 모양은 러프하게 다름을 확인할 수 있습니다.

 

어떻게 이런 건지 다음 과정을 통해서 확인해 보도록 하겠습니다.

 

위 파이썬 코드에 몇 가지 확인 과정을 추가해 보겠습니다.

 

우선 중간에 코드를 나눠서 df 데이터 셋에 어떤 데이터가 들어있는지 확인해 보겠습니다.

데이터를 확인해 보닌 깐, dataset이라는 칼럼이 있고, x , y 컬럼이 뒤에 있습니다.

 

dataset에는 I, II, III, IV 라는 값이 11개씩 들어가 있습니다.

 

첨에 우리가 그린 그래프는 위 dataset 에 있는 4개의 데이터 셋으로 그린 각각의 그래프입니다.

 

다음은, df 데이터 셋에 데이터가 얼마나 있는지도 확인해 보아야겠죠?

df 데이터 셋 전체의 describe 도 확인해 보겠습니다.

df 데이터 셋을 보면 선두에 dataset이라는 칼럼이 있습니다.

 

dataset 칼럼의 값이 "I"인 데이터 셋의 describe를 확인해 보겠습니다.

 

위와 같이 describe가 나옵니다.

 

그럼 우리 dataset의 값이 "II" 인 것도 확인해 보아야겠습니다.

어떠신가요? 첫 번째와 두 번째, 데이터의 describe가 같음을 확인할 수 있습니다. min, max를 제외하고선 말이죠.

 

그럼 상관계수도 같은지 확인을 해보겠습니다.

이렇게 I, II, III, IV 각각 11개씩 들어있는 데이터 셋의 상관계수 역시 거의 흡사하다는 것을 확인할 수 있습니다.

 

이렇게 확인한 결과 4개의 데이터 셋의 각각의 데이터의 값은 다르지만, 평균, 표준편차, 상관계수, 회귀 값은같다~!

 

그래서 Anscombe's quartet에서 산점도는 다르지만, 러프하게 그려지는 회귀선의 그래프는 같다 라는 겁니다.

 

 

자, 다음은 lmplot을 이용해서 그래프를 이용한 시각화 방법에 대해서 실습, 설명해 보겠습니다.

 

위와 이어서 아래와 같이 코드를 입력해 봅니다.

위의 그래프는 df 데이터 셋에서 dataset 칼럼을 구분하지 않고 하나의 셋으로 그린 그래프입니다.

 

그리고 아래 그래프는 hue 옵션을 입력하여 dataset 값을 기준으로 다른 색상으로 그래프를 겹치게

 

그려놓은 모습임을 확인할 수 있습니다.

 

겹치지 않고 따로따로 보는 게 좋겠죠? 그럴 땐 col 옵션을 사용합니다.

 

이렇게 col 옵션을 사용해서 그래프를 따로따로 그릴 수 있습니다.

 

다음은, 위 그래프에 있는 그림자 영역에 대한 옵션입니다.

 

그림자처럼 표현된 곳은 데이터 분포에 대한 신뢰구간을 표시한 것인데요, 이걸 옵션으로 삭제할 수도 있고,

 

양 극단을 제외하고 보이게도 할 수 있습니다.

 

젤 윗줄은 ci 옵션을 별도로 주지 않은 경우 (ci=100)과 동일합니다.

 

가운데는 ci=None 옵션, 그리고 마지막은 ci=50의 옵션을 준 그래프입니다.

 

시각화를 하면서 ci 옵션을 유용하게 사용할 수 있을 것 같습니다.

 

자, 다음은 지금 나오는 그래프들은 한 줄에 4개가 나오는데, 우리가 위에서 실행했을 땐 2*2로 나왔던걸 기억하시죠?

 

그렇게 나오게 하려면 어떤 옵션이 필요 한지 확인해 보겠습니다.

이렇게 col_wrap=2 옵션을 이용하면 2*2로 나오게 할 수 있습니다.

 

그래프가 많이 나와야 할 때 유용하게 쓰일 수 있는 옵션입니다.

 

더불에 위에서 나온 다른 옵션들 중에 palette와 height가 있는데 예상하시는 그대로입니다.

 

palette는 그래프 색상을 지정할 수 있는 옵션이고, height 옵션을 통해서 그래프의 높이를 변경할 수 있습니다.

 

마지막으로 scatter_kws 옵션에 대해서 확인해 보겠습니다.

위 그래프 2개는 각각의 scatter_kws의 alpha 값을 다르게 한 결과입니다.

 

바로 산점도로 표시되어 있는 점들의 투명도를 조절하는 옵션입니다.

 

그럼 scatter_kws의 s 값은 어떤 옵션인지 확인해보아야겠죠?

 

딱 보면 아시겠지만 이것 역시 산점도로 표현되는 점들의 크기를 지정하는 옵션입니다.

 

이것 외에도 lmplot 은 많은 옵션을 가지고 있는데 아래에 한번 정리해두겠습니다.

더보기

Parameters
----------
x, y : strings, optional
    Input variables; these should be column names in ``data``.

data : DataFrame
    Tidy ("long-form") dataframe where each column is a variable and each
    row is an observation.    

hue, col, row : strings
    Variables that define subsets of the data, which will be drawn on
    separate facets in the grid. See the ``*_order`` parameters to control
    the order of levels of this variable.

palette : palette name, list, or dict, optional
    Colors to use for the different levels of the ``hue`` variable. Should
    be something that can be interpreted by :func:`color_palette`, or a
    dictionary mapping hue levels to matplotlib colors.    

col_wrap : int, optional
    "Wrap" the column variable at this width, so that the column facets
    span multiple rows. Incompatible with a ``row`` facet.    

height : scalar, optional
    Height (in inches) of each facet. See also: ``aspect``.    

aspect : scalar, optional
    Aspect ratio of each facet, so that ``aspect * height`` gives the width
    of each facet in inches.    

markers : matplotlib marker code or list of marker codes, optional
    Markers for the scatterplot. If a list, each marker in the list will be
    used for each level of the ``hue`` variable.

share{x,y} : bool, 'col', or 'row' optional
    If true, the facets will share y axes across columns and/or x axes
    across rows.    

{hue,col,row}_order : lists, optional
    Order for the levels of the faceting variables. By default, this will
    be the order that the levels appear in ``data`` or, if the variables
    are pandas categoricals, the category order.

legend : bool, optional
    If ``True`` and there is a ``hue`` variable, add a legend.

legend_out : bool, optional
    If ``True``, the figure size will be extended, and the legend will be
    drawn outside the plot on the center right.    

x_estimator : callable that maps vector -> scalar, optional
    Apply this function to each unique value of ``x`` and plot the
    resulting estimate. This is useful when ``x`` is a discrete variable.
    If ``x_ci`` is given, this estimate will be bootstrapped and a
    confidence interval will be drawn.    

x_bins : int or vector, optional
    Bin the ``x`` variable into discrete bins and then estimate the central
    tendency and a confidence interval. This binning only influences how
    the scatterplot is drawn; the regression is still fit to the original
    data.  This parameter is interpreted either as the number of
    evenly-sized (not necessary spaced) bins or the positions of the bin
    centers. When this parameter is used, it implies that the default of
    ``x_estimator`` is ``numpy.mean``.    

x_ci : "ci", "sd", int in [0, 100] or None, optional
    Size of the confidence interval used when plotting a central tendency
    for discrete values of ``x``. If ``"ci"``, defer to the value of the
    ``ci`` parameter. If ``"sd"``, skip bootstrapping and show the
    standard deviation of the observations in each bin.    

scatter : bool, optional
    If ``True``, draw a scatterplot with the underlying observations (or
    the ``x_estimator`` values).    

fit_reg : bool, optional
    If ``True``, estimate and plot a regression model relating the ``x``
    and ``y`` variables.    

ci : int in [0, 100] or None, optional
    Size of the confidence interval for the regression estimate. This will
    be drawn using translucent bands around the regression line. The
    confidence interval is estimated using a bootstrap; for large
    datasets, it may be advisable to avoid that computation by setting
    this parameter to None.    

n_boot : int, optional
    Number of bootstrap resamples used to estimate the ``ci``. The default
    value attempts to balance time and stability; you may want to increase
    this value for "final" versions of plots.    

units : variable name in ``data``, optional
    If the ``x`` and ``y`` observations are nested within sampling units,
    those can be specified here. This will be taken into account when
    computing the confidence intervals by performing a multilevel bootstrap
    that resamples both units and observations (within unit). This does not
    otherwise influence how the regression is estimated or drawn.    

order : int, optional
    If ``order`` is greater than 1, use ``numpy.polyfit`` to estimate a
    polynomial regression.    

logistic : bool, optional
    If ``True``, assume that ``y`` is a binary variable and use
    ``statsmodels`` to estimate a logistic regression model. Note that this
    is substantially more computationally intensive than linear regression,
    so you may wish to decrease the number of bootstrap resamples
    (``n_boot``) or set ``ci`` to None.    

lowess : bool, optional
    If ``True``, use ``statsmodels`` to estimate a nonparametric lowess
    model (locally weighted linear regression). Note that confidence
    intervals cannot currently be drawn for this kind of model.    

robust : bool, optional
    If ``True``, use ``statsmodels`` to estimate a robust regression. This
    will de-weight outliers. Note that this is substantially more
    computationally intensive than standard linear regression, so you may
    wish to decrease the number of bootstrap resamples (``n_boot``) or set
    ``ci`` to None.    

logx : bool, optional
    If ``True``, estimate a linear regression of the form y ~ log(x), but
    plot the scatterplot and regression model in the input space. Note that
    ``x`` must be positive for this to work.    

{x,y}_partial : strings in ``data`` or matrices
    Confounding variables to regress out of the ``x`` or ``y`` variables
    before plotting.    

truncate : bool, optional
    By default, the regression line is drawn to fill the x axis limits
    after the scatterplot is drawn. If ``truncate`` is ``True``, it will
    instead by bounded by the data limits.    

{x,y}_jitter : floats, optional
    Add uniform random noise of this size to either the ``x`` or ``y``
    variables. The noise is added to a copy of the data after fitting the
    regression, and only influences the look of the scatterplot. This can
    be helpful when plotting variables that take discrete values.    

{scatter,line}_kws : dictionaries
    Additional keyword arguments to pass to ``plt.scatter`` and
    ``plt.plot``.    

자, 오늘은 이렇게 seaborn 라이브러리에 대해서 한번 실습을 해봤습니다.

 

물론 여기 정리된 것보다 훨씬 많은 내용을 가지고 있는 seaborn 라이브러리지만, 대표적인 것을 정리해보았습니다.

 

아마, 첨부터 따라 하시다 보면 그래도 이것 하나만큼은 확실하게 알고 갈 수 있을 거라고 생각합니다.

 

이렇게 데이터 시각화에 또 한걸음 다가가는 거죠.

 

오늘 실습은 아래 youtube 영상을 참고로 했습니다.

 

 

오늘 하루도 좋은 하루 되시고! 파이팅하시기 바랍니다!! 감사합니다!!

 

 

by.sTricky