-
[혼공분석] 6주차_코딩은 40대 후반부터~카테고리 없음 2025. 2. 2. 19:59
[ 기본 숙제(필수) ]
1. p. 344의 손코딩(맷플롯립의 컬러맵으로 산점도 그리기)을 코랩에서 그래프 출력하고 화면 캡처하기
① matplotlib, ② seaborn, ③ plotly 라이브러리를 활용하여 그래프를 출력하고 화면 캡쳐하기 완료
④ chart_studio 라이브러리를 활용하여 이미지 형태의 그래프가 아닌 interactive 그래프까지 출력!
① matplotlib
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(10, 8)) ax.scatter(ns_book8['발행년도'], ns_book8['출판사'], linewidths=0.5, edgecolors='k', alpha=0.3, s=ns_book8['대출건수']*2, c=ns_book8['대출건수']) ax.set_title('출판사별 발행 도서') fig.show()
② seaborn
import seaborn as sns import matplotlib.pyplot as plt plt.figure(figsize=(10, 8)) sns.scatterplot(x='발행년도', y='출판사', size='대출건수', hue='대출건수', data=ns_book8, linewidths=0.5, edgecolors='k', alpha=0.3, sizes=(ns_book8['대출건수'].min() * 2, ns_book8['대출건수'].max() * 2)) plt.title('출판사별 발행 도서') plt.show()
③ plotly
import plotly.express as px fig = px.scatter( ns_book8, x='발행년도', y='출판사', size='대출건수', color='대출건수', title='출판사별 발행 도서', opacity=0.3, # Corresponds to alpha ) # Customize layout if needed fig.update_traces(marker=dict(line=dict(width=0.5, color='black'))) # set edgecolor and linewidth fig.update_layout(width=1000, height=800, title_x = 0.5, title_y = 0.9, title_xanchor = "center", title_yanchor = "middle") fig.show()
④ chart_studio : Plotly에서 개발한 서비스로 웹을 기반으로 Plotly 그래프 생성 및 Raw 데이터 수정까지 가 Chart Studio를 사용하면 Dash를 쓰지 않고 Plotly 그래프를 HTML 형태로 내보낼 수 있다고 해서 도전!
♥ 아래의 html로 삽입된 plotly 기반 그래프를 보면 colab에서 보는 것과 같이 interactive하게 반응 ♥
!pip install chart_studio import chart_studio username = 'gijunge' api_key = '####################' chart_studio.tools.set_credentials_file(username=username, api_key=api_key) import plotly.express as px fig = px.scatter( ns_book8, x='발행년도', y='출판사', size='대출건수', color='대출건수', title='출판사별 발행 도서', opacity=0.3, # Corresponds to alpha ) # Customize layout if needed fig.update_traces(marker=dict(line=dict(width=0.5, color='black'))) # set edgecolor and linewidth fig.update_layout(width=750, height=600, title_x = 0.5, title_y = 0.9, title_xanchor = "center", title_yanchor = "middle") fig.show() import chart_studio.plotly as py py.plot(fig, filename = '출판사별 발행 도서', auto_open=True) import chart_studio.tools as tls tls.get_embed('https://plotly.com/~gijunge/14/')
[ 추가 숙제(필수) ]
1. p. 356 ~ 359의 스택 영역 그래프를 그리는 과정을 정리하기
① matplotlib 라이브러리를 활용하여 stack area 그래프를 출력하고 화면 캡쳐하기 완료
② plotly/chart_studio 라이브러리를 활용하여 이미지 형태의 그래프가 아닌 interactive 그래프까지 tistory에 삽입!
top30_pubs = ns_book7['출판사'].value_counts()[:30] top30_pubs_idx = ns_book7['출판사'].isin(top30_pubs.index) ns_book9 = ns_book7[top30_pubs_idx][['출판사', '발행년도', '대출건수']] ns_book9 = ns_book9.groupby(by=['출판사', '발행년도']).sum().reset_index() # 혼공분석 책에서는 pivot_table()메서드를 사용하여 get_level_values()메서드로 연도로 구성된 두 번째 항목만 가져왔지만, crosstab()메서드를 사용하면 get_level_values()메서드를 사용하지 않고도 원하는 결과를 얻을 수 있다~! ns_book10 = pd.crosstab(index=ns_book9['출판사'], columns=ns_book9['발행년도'], values=ns_book9['대출건수'], aggfunc='sum') ns_book10.head() top10_pubs = top30_pubs.index[:10] fig, ax = plt.subplots(figsize=(8, 6)) ax.stackplot(ns_book10.columns, ns_book10.loc[top10_pubs].fillna(0), labels=top10_pubs) ax.set_title('연도별 대출건수') ax.legend(loc='upper left') ax.set_xlim(1985, 2025) fig.show()
② plotly/chart_studio 라이브러리를 활용하여 이미지 형태의 그래프가 아닌 interactive 그래프까지 tistory에 삽입!
- 우선은 plotly 라이브러리를 활용하여 interactive 그래프까지 구현해보고
import plotly.express as px # Filter for the top 10 publishers # plotly 라이브러리를 활용하여 stack area graph를 그릴 때는 crosstab()메서드를 사용하지 않고 DataFrame 형태로 활용함! ns_book9 = ns_book9[ns_book9['출판사'].isin(top10_pubs)] fig = px.area(ns_book9, x='발행년도', y='대출건수', color='출판사', line_group='출판사') # Set x-axis range fig.update_xaxes(range=[1985, 2025]) # Adjust the range as needed # Align legend to top left fig.update_layout(width=750, height=600, legend=dict(x=0.01, y=0.99, yanchor='top')) fig.show()
- chart_studio ♥ 아래의 html로 삽입된 plotly 기반 그래프를 보면 colab에서 보는 것과 같이 interactive하게 반응 ♥
!pip install chart_studio import chart_studio username = 'gijunge' api_key = '####################' chart_studio.tools.set_credentials_file(username=username, api_key=api_key) import plotly.express as px # Filter for the top 10 publishers ns_book9 = ns_book9[ns_book9['출판사'].isin(top10_pubs)] fig = px.area(ns_book9, x='발행년도', y='대출건수', color='출판사', line_group='출판사') # Set x-axis range fig.update_xaxes(range=[1985, 2025]) # Adjust the range as needed # Align legend to top left fig.update_layout(width=750, height=500, legend=dict(x=0.01, y=0.99, yanchor='top')) fig.show() import chart_studio.plotly as py py.plot(fig, filename = '연도별 대출건수', auto_open=True) import chart_studio.tools as tls tls.get_embed('https://plotly.com/~gijunge/18/')