Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

데이터분석 공부하기

[시각화] Matplotlib & Seaborn 본문

Python

[시각화] Matplotlib & Seaborn

Eileen's 2021. 10. 19. 15:19

[Matplotlib VS Matlab VS Seaborn]

  • Matplotlib vs. Matlab
    - Matplotlib : a python visualization library. It is made to work like matlab.
    - Matlab : numerical computing environment and programming language (best for engineer/scientist)
  • Seaborn : extension to matplotlib(need to be imported together)
                     It
    introduces additional plot types and visual improvement. 

[Basics : Figure & Axes]

  • f, ax (figure, axes)
    -f(=figure)는 fig = plt.figure()와 같이 그래프를 그리기 전 도화지를 만드는 작용을 한다. 
    -figure를 추가하는 이점 : useful to change figure level attribute or save the figure as a image file later on 
  • *도화지 생성 3가지 방법*
    1) f = plt.figure(figsize = (10,10)) #axes 안받음
    2) f, ax = plt.subplots(1, 1, figsize = (10,10)) # ax.plot(a)로 나중에 축을 그림
    3) plt.figure(figsize = (10,10)) #plt.plot()
    f, ax = plt.subplots(1,2, figsize = (7,3))
    train.Survived.value_counts().plot.pie(explode = [0,0.1], autopct = '%.1f%%', ax=ax[0], shadow = True)
    ax[0].set_title('Pie plot - Survived')
    ax[0].set_ylabel('')
    
    sns.countplot('Survived', data = train, ax=ax[1])
    ax[1].set_title('Count plot - Survived')
    ax[1].set_ylabel('')
    ax[1].set_xlabel('')
    plt.show()​

 

[Style Setting]

-plt.rcParams를 사용하면 전역에 style을 적용할 수 있다.

plt.rcParams['figure.figsize'] = (20,10)

1. xticks
-xticks label 각도 변경(가로로 되어 겹치는 경우 유용)

plt.xticks(rotation=270)

 

2. Annotate

plt.bar(top10_on.index, top10_on['평균승차인원수'])

for x, y in enumerate(list(top10_on['평균승차인원수'])):
    if x == 0:
        plt.annotate(y, (x-0.15, y), color = 'red')
    else:
        plt.annotate(y, (x-0.15, y))

plt.title('2021년 6월 평균 승차 인원 수 Top10')
plt.show()

 

 

 

[결측치 시각화]

  • Missingno : 결측치 시각화. Seaborn보다 더 다각도로 시각화 가능
    1) Matrix, 2) Bar Chart, 3) Heatmap, 4) Dendrogram
    import missingno as msno

[분포 시각화]

  • distplot : histogram 생성
    fig, ax = plt.subplots(1,1,figsize= (6,6))
    sns.distplot(train['Fare'], color = 'b', label = 'Skewness : {:.2f}'.format(train['Fare'].skew(), ax=ax))
    plt.legend(loc='upper right', fontsize = 'x-large')
  • kdeplot : Kernel Density Estimation(데이터의 분포) -> distribution을 보여주는 graph
sns.kdeplot(train['Age'])
plt.title('Destribution of Age')
plt.show()
  • violinplot :  categorical variables의 데이터 분포를 볼 수 있는 graph
    f, ax = plt.subplots(1,2, figsize=(10,8))
    
    #plt.rc('axes', labelsize = 4)
    
    sns.violinplot('Pclass', 'Age', hue = 'Survived', data = train, scale = 'count', split = True, ax = ax[0])
    ax[0].set_title('Sex x Pclass on Survived')
    ax[0].set_yticks(range(0,110,10))
    #ax[0].tick_params(labelsize = 10)
    
    
    sns.violinplot('Sex', 'Age', hue = 'Survived', data = train, scale = 'count', split = True, ax = ax[1])
    ax[1].set_title('Sex x Age on Survived')
    ax[1].set_yticks(range(0,110,10))
    #ax[1].tick_params(labelsize = 10)
    
    plt.subplots_adjust(wspace = 0.7, hspace = 0.5)
    plt.show()

 

[변수 간 관계 시각화]

  • heatmap : 상관관계를 볼 수 있는 graph; MultiColinearity를 찾아 불필요한 feature 제거
heatmap_data = train[['Survived','Pclass','Sex', 'initial',
                      'Fare','Embarked','Family','Age_ord']]
colormap = plt.cm.coolwarm
plt.figure(figsize= (7,5))
plt.title('Pearson Coerrelation of Features', y =1.02, size = 15)
sns.heatmap(heatmap_data.astype(float).corr(), cmap = colormap, vmax = 1, 
            vmin = -1,linewidth = 0.2, linecolor = 'white', annot = True, 
            annot_kws = {'size' : 9}, fmt = '.2f' )

 

  • factorplot : categorical variables간의 관계를 볼 수 있는 graph
    sns.factorplot('Pclass','Survived',hue = 'Sex', data = train, size = 6, aspect = 1.5)​