Lesson 10: seaborn, plotnine

Author

최규빈

Published

July 26, 2023

{{< https://youtu.be/playlist?list=PLQqh36zP38-yg8czkU9rHuXOKBKBjYvtT&si=iqY8uqljExE9yogq >}}

Imports

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from plotnine import *
import matplotlib
matplotlib.rcParams['figure.dpi'] = 120
# import warnings
# warnings.filterwarnings('ignore')

Seaborn

- 개념차이

  • matplotlib: 벡터 친화적
  • seaborn: 데이터프레임 친화적

- 데이터프레임 친화적인 시각화 툴이 왜 강력한가?

  • 분석할 데이터가 tabula data 형식인 경우가 많다.
  • matplotlib은 여전히 강력하지만, seaborn등 데이터프레임 친화적 패키지가 우수한 경우가 많다.
df = pd.read_csv("https://raw.githubusercontent.com/guebin/DV2023/main/posts/titanic.csv")
df.head()
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked logFare
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S 1.981001
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C 4.266662
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S 2.070022
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S 3.972177
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S 2.085672
s = df[df['Survived'] ==1].Sex
s
1      female
2      female
3      female
8      female
9      female
        ...  
875    female
879    female
880    female
887    female
889      male
Name: Sex, Length: 342, dtype: object
sns.scatterplot(
    df,
    x='logFare',
    y='Age',
    hue='Sex',
    style='Survived',style_order=[1,0],
    alpha=0.8
)

plt.hist(df.Age);
plt.hist(df.Age[df.Survived==1]);

훌륭한 시각화

애드워드 터프티

- 데이터 시각화계의 거장

- 터프티의 이론중 백미: 엄격한 미니멀리즘

  • 최소한의 잉크로 많은 정보를 전달할 수 있다면 그것이 바로 좋은 그래프이다.
  • 작은 지면 내에서 잉크를 최대한 적게 써서 짧은 시간 안에 많은 영감을 주어야 한다.

- 데이터-잉크비: 데이터를 표현하는데 들아가는 잉크의 양 / 그래픽을 인쇄하는데 들어가는 잉크의 총량

- 차트정크 (나이젤홈즈의 그래프)

“Lurking behind chartjunk is contempt both for information and for the audience. Chartjunk promoters imagine that numbers and details are boring, dull, and tedious, requiring ornament to enliven. Cosmetic decoration, which frequently distorts the data, will never salvage an underlying lack of content. If the numbers are boring, then you’ve got the wrong numbers (…) Worse is contempt for our audience, designing as if readers were obtuse and uncaring. In fact, consumers of graphics are often more intelligent about the information at hand than those who fabricate the data decoration (…) The operating moral premise of information design should be that our readers are alert and caring; they may be busy, eager to get on with it, but they are not stupid.”

  • 차트정크 = 대중을 멸시 + 데이터에 대한 모독
  • 차트정크 옹호가는 숫자와 데이터가 지루하여 활기가 필요하다고 생각하는 모양이다..

- 별로인 그래프 (왼쪽) / 우수한 그래프 오른쪽

- 별로인 그래프 (왼쪽) / 우수한 그래프 오른쪽

- 별로인 그래프 (왼쪽) / 우수한 그래프 오른쪽

- 제 생각: 글쎄…

찰스미나드의 도표

  • 인류역사상 가장 훌륭한 시각화

- 터프티의 평

  • 지금까지 그려진 최고의 통계 그래픽일지도 모른다.
  • 여기에서는 군대의 크기, 2차원 평면상의 위치, 군대의 이동방향, 모스코바에서 퇴각하는 동안의 여러날짜, 온도 \(\to\) 6차원의 변수
  • 백만번에 한번 이런 그림을 그릴수는 있겠지만 이러한 멋진 그래픽을 만드는 방법에 대한 원칙은 없다. \(\to\) 미니멀리즘..

- 왜 우수한 그래프일까?

  • 자료를 파악하는 기법은 최근까지도 산점도, 막대그래프, 라인플랏에 의존
  • 이러한 플랏의 단점은 고차원의 자료를 분석하기 어렵다는 것임
  • 미나드는 여러그림을 그리는 방법 대신에 한 그림에서 패널을 늘리는 방법을 선택함.