카테고리 없음

1-6) 파이썬 데이터 분석 기초 스터디

intergem 2025. 3. 30. 22:33

강의명 : 5분빨리 퇴근하자! 파이썬 데이터 분석, 시각화, 웹 대시보드 제작하기

플랫폼 : 인프런

 

 

9) 그래프 세부 요소 튜닝하기

  • Matplotlib tick label 회전, 글씨 크기 조절
    • tick_params 인자 사용
    • tick_params(axis, 변경 인자)
    fig, ax= plt.subplots() 
    
    sns.boxplot(
     x='company_location', y='salary_in_usd',
     data=df_10companies, ax=ax
    )
    
    ax.tick_params(axis='x', labelrotation=90)
    
    • figure의 update_xaxes, update_yaxes 인자 사용
    fig = px.box(
        data_frame=df_10companies, x='company_location', y='salary_in_usd', 
        width=500, height=400
    )
    **fig.update_xaxes(tickfont={'size':16}, tickangle=90)** 
    fig.show()
    
  • Matplotlib 그래프 제목 입력
    • 각 ax에서 set_title 메서드 사용
    df = pd.read_csv('../datasets/ds_salaries/ds_salaries.csv') 
    
    fig, ax= plt.subplots(1, 3, figsize=(15, 5))
    sns.boxplot(x='company_size', y='salary_in_usd', data=df, **ax=ax[0], order=['S','M','L']**) 
    **ax[0].set_title('company_size box plot', fontsize=16)**
    
    sns.histplot(x='salary_in_usd', data=df, **ax=ax[1]**) 
    **ax[1].set_title('salary histogram', fontsize=16)**
    
    pivot_df = df.pivot_table(
    index='company_size', columns='experience_level', values='salary_in_usd', aggfunc='mean'
    )
    
    sns.heatmap(pivot_df, ax=ax[2], annot=True)
    **ax[2].set_title('heatmap of\\nexperience_level x company_size', fontsize=16)**
    
  • Plotly 그래프 제목 입력
    • Plotly express 그래프 함수 내에서 title 인자 사용
    • HTML 요소 사용하여 굵기, 이탤릭체 등 수정 가능
    • figure의 update_layout 함수 사용하여 글꼴, 크기 등 세부 사항 수정 가능
     fig = px.box(
      data_frame=df, x='company_size', y='salary_in_usd', width=400, height=400,
      **title='<b>company_size box plot</b>'**, category_orders={'company_size':['S','M','L']}
    ) 
    
    **fig.update_layout({'title_font_size':20})** 
    fig.show()
    
  • Matplotlib_Grid
    • 각 축의 값을 보다 편하게 읽기 위해 도움을 주는 눈금선
    • Matplotlib에서 ax의 grid 메서드 사용
    fig, ax= plt.subplots()
    
    sns.boxplot(
    x='company_size', y='salary_in_usd', data=df, ax=ax, order=['S','M','L']
    )
    ax.set_title('company_size box plot', fontsize=16) 
    **ax.grid(axis='y')**
    
  • Matplotlib_Plotly
    • Plotly의 기본 테마에서 grid는 기본 값으로 설정되어 있음
    • Plotly에서 grid를 제거하기 위해 update_layout 메서드 사용
    fig = px.box(
        df, x='company_size', y='salary_in_usd',
        height=400, width=400
    )
    **fig.update_layout(yaxis={'showgrid':False})** 
    fig.show()
    
  • Subplot 위치 조절
    • 정해진 크기의 figure에서 각 subplot들의 크기에 따라 그래프가 겹칠 수 있 음
    • Matplotlib tight_layout 메서드 사용하여 subplot 간 간격 조절
    fig, ax = plt.subplots(2, 2)
    for idx in range(2):
       for jdx in range(2): 
         ax[idx][jdx].set_xlabel('x_label') 
         ax[idx][jdx].set_ylabel('y_label') 
         ax[idx][jdx].set_title('title')
    

    • Matplotlib tight_layout 메서드 사용하여 subplot 간 간격 조절
  • Subplot 위치 조절_Plotly
    • 정해진 크기의 figure에서 각 subplot들의 크기에 따라 그래프가 겹칠 수 있 음
    • Plotly express 그래프 함수의 facet_col_spacing, facet_row_spacing 메서드 사용하여 subplot 간 간격 조절
  • Matplotlib tick label 회전, 글씨 크기 조절
    • tick_params 인자 사용
    • tick_params(axis, 변경 인자)
    fig, ax= plt.subplots() 
    
    sns.boxplot(
     x='company_location', y='salary_in_usd',
     data=df_10companies, ax=ax
    )
    
    ax.tick_params(axis='x', labelrotation=90)
    
    • figure의 update_xaxes, update_yaxes 인자 사용
    fig = px.box(
        data_frame=df_10companies, x='company_location', y='salary_in_usd', 
        width=500, height=400
    )
    **fig.update_xaxes(tickfont={'size':16}, tickangle=90)** 
    fig.show()
    
  • Matplotlib 그래프 제목 입력
    • 각 ax에서 set_title 메서드 사용
    df = pd.read_csv('../datasets/ds_salaries/ds_salaries.csv') 
    
    fig, ax= plt.subplots(1, 3, figsize=(15, 5))
    sns.boxplot(x='company_size', y='salary_in_usd', data=df, **ax=ax[0], order=['S','M','L']**) 
    **ax[0].set_title('company_size box plot', fontsize=16)**
    
    sns.histplot(x='salary_in_usd', data=df, **ax=ax[1]**) 
    **ax[1].set_title('salary histogram', fontsize=16)**
    
    pivot_df = df.pivot_table(
    index='company_size', columns='experience_level', values='salary_in_usd', aggfunc='mean'
    )
    
    sns.heatmap(pivot_df, ax=ax[2], annot=True)
    **ax[2].set_title('heatmap of\\nexperience_level x company_size', fontsize=16)**
    
  • Plotly 그래프 제목 입력
    • Plotly express 그래프 함수 내에서 title 인자 사용
    • HTML 요소 사용하여 굵기, 이탤릭체 등 수정 가능
    • figure의 update_layout 함수 사용하여 글꼴, 크기 등 세부 사항 수정 가능
     fig = px.box(
      data_frame=df, x='company_size', y='salary_in_usd', width=400, height=400,
      **title='<b>company_size box plot</b>'**, category_orders={'company_size':['S','M','L']}
    ) 
    
    **fig.update_layout({'title_font_size':20})** 
    fig.show()
    
  • Matplotlib_Grid
    • 각 축의 값을 보다 편하게 읽기 위해 도움을 주는 눈금선
    • Matplotlib에서 ax의 grid 메서드 사용
    fig, ax= plt.subplots()
    
    sns.boxplot(
    x='company_size', y='salary_in_usd', data=df, ax=ax, order=['S','M','L']
    )
    ax.set_title('company_size box plot', fontsize=16) 
    **ax.grid(axis='y')**
    
  • Matplotlib_Plotly
    • Plotly의 기본 테마에서 grid는 기본 값으로 설정되어 있음
    • Plotly에서 grid를 제거하기 위해 update_layout 메서드 사용
    fig = px.box(
        df, x='company_size', y='salary_in_usd',
        height=400, width=400
    )
    **fig.update_layout(yaxis={'showgrid':False})** 
    fig.show()
    
  • Subplot 위치 조절
    • 정해진 크기의 figure에서 각 subplot들의 크기에 따라 그래프가 겹칠 수 있 음
    • Matplotlib tight_layout 메서드 사용하여 subplot 간 간격 조절
    fig, ax = plt.subplots(2, 2)
    for idx in range(2):
       for jdx in range(2): 
         ax[idx][jdx].set_xlabel('x_label') 
         ax[idx][jdx].set_ylabel('y_label') 
         ax[idx][jdx].set_title('title')
    

    • Matplotlib tight_layout 메서드 사용하여 subplot 간 간격 조절
  • Subplot 위치 조절_Plotly
    • 정해진 크기의 figure에서 각 subplot들의 크기에 따라 그래프가 겹칠 수 있 음
    • Plotly express 그래프 함수의 facet_col_spacing, facet_row_spacing 메서드 사용하여 subplot 간 간격 조절
    df = sns.load_dataset('tips')
    fig = px.scatter(
        df, x='total_bill', y='tip', facet_row='sex', facet_col = 'time',
        width=600, height=600, 
        **facet_row_spacing=0.2, facet_col_spacing=0.1**
    ) 
    fig.show()
    
  • df = sns.load_dataset('tips') fig = px.scatter( df, x='total_bill', y='tip', facet_row='sex', facet_col = 'time', width=600, height=600, **facet_row_spacing=0.2, facet_col_spacing=0.1** ) fig.show()

 

4. Matplotlib, Seaborn, Plotly 라이브러리 실전 꿀팁 대방출

1) 시계열 그래프 tick label 깔끔하게 표현하기

  • 날짜/시간 데이터를 축으로 하는 그래프
    • 날짜/시간 관련 column을 그래프의 축 변수로 사용할 경우 데이터 타입 확인 필요
    • object 타입인 경우 아래 그림처럼 알아볼 수 없게 나올 수 있음
    **#tick_params 회전**
    fig, ax = plt.subplots()
    sns.lineplot(x='Date', y='Close', data=df, ax=ax)
    **ax.tick_params(axis='x', labelrotation=90)**
    
    • (추천) matplotlib 라이브러리의 ConciseDateFormatter 이용하여 보다 깔끔하게 변경 가능
    import matplotlib as mpl
    fig, ax = plt.subplots()
    sns.lineplot(x='Date', y='Close', data=df, ax=ax)
    **ax.xaxis.set_major_formatter(
        mpl.dates.ConciseDateFormatter(ax.xaxis.get_major_locator() ))**
    
  • Plotly
    • Plotly의 경우 날짜/시간 관련 자동 parsing
    • figure의 update_xaxes 메서드의 tickformat 인자를 통해 날짜/시간 형식 지정 가능
    fig = px.line(df, x='Date', y='Close', width=500, height=400)
    **fig.update_xaxes(tickformat='%Y-%m-%d')**
    fig.show()
    

2) 다중 축 그래프 그리기

  • 2개의 y축을 가지는 그래프 그리기
    • 첫 번째 ax에 twinx 메서드 이용하여 두 번째 ax2 변수 설정
    • 두 개의 ax, ax2에 각각 그래프 그리기
    fig, ax = plt.subplots()
    **ax2 = ax.twinx()**
    sns.lineplot(x='Date', y='Close', data=df, ax=ax, color='red')
    sns.lineplot(x='Date', y='Volume', data=df, ax=ax2, color='blue')
    
    ax.tick_params(axis='y', labelcolor='red')
    ax.yaxis.label.set_color('red')
    
    ax2.tick_params(axis='y', labelcolor='blue')
    ax2.yaxis.label.set_color('blue')
    
    ax.xaxis.set_major_formatter(
        mpl.dates.ConciseDateFormatter(
            ax.xaxis.get_major_locator()
        )
    )
    
  • Plotly
    • plotly subplots의 make_subplots 함수 이용
    • 두 개의 plotly express 그래프를 그려 다른 변수에 할당 후, add_traces를 이용해 figure에 합치는 방식
    from plotly.subplots import make_subplots
    
    fig = **make_subplots(specs=[[{"secondary_y":True}]])**
    
    subfig1 = px.line(df, x='Date', y='Close')
    subfig1.update_traces(line_color='red')
    subfig2 = px.line(df, x='Date', y='Volume')
    subfig2.update_traces(line_color='blue')
    
    subfig2.update_traces(yaxis='y2')
    
    **fig.add_traces(subfig1.data + subfig2.data)**
    
    fig.layout.xaxis.title = 'Date'
    fig.layout.yaxis.title = 'Close'
    fig.layout.yaxis2.title = 'Volume'
    fig.layout.yaxis.color = 'red'
    fig.layout.yaxis2.color = 'blue'
    
    fig.update_layout(width=500, height=400)
    fig.show()