판다스 입문

판다스 입문(데이터 프레임,시리즈로 그래프 그리기/seaborn 라이브러리로 그래프 스타일 설정하기)

jaeyoonlee 2021. 3. 20. 16:13

#9 판다스 chapter 9. 그래프 그리기-데이터프레임과 시리즈로 그래프그리기/seaborn 라이브러리로 그래프 스타일 설정하기

데이터프레임과 시리즈로 그래프 그리기

데이터 프레임과 시리즈로도 그래프를 그릴 수 있다.

 

1) 먼저 히스토그램을 그려보자. 시리즈에 있는 plot 속서에 정의된 hist 메서드를 사용하면 해당 시리즈의 값을 이용하여 히스토그램을 바로 그릴 수 있다.

 

ax = plt.subplot()
ax = tips['total_bill'].plot.hist()

 

 

2) 투명도를 조절하려면 hist 메서드의 alpha, bins, ax 인자를 사용하면 된다. 다음은 tips 데이터프레임에서 2개의 시리즈를 선택하여 히스토그램을 그린 것이다.

 

 

3) 밀집도, 산점도 그래프, 육각 그래프는 각각 kde, scatter, hexbin 메서드를 사용하여 그릴 수 있다.

 

ax = plt.subplots()
ax = tips['tip'].plot.kde()

 

 

fig, ax = plt.subplots()
ax = tips.plot.scatter(x='total_bill', y='tip', ax=ax)

 

 

fig, ax = plt.subplots()
ax = tips.plot.hexbin(x='total_bill', y='tip', ax=ax)

 

 

4) 이때 육각 그래프의 육각형 크기는 gridsize 인자를 사용하여 변경할 수 있다.

 

fig, ax = plt.subplots()
ax = tips.plot.hexbin(x='total_bill', y='tip', gridsize=10, ax=ax)

 

 

5) 다음은 box 메서드를 사용하여 그린 박스 그래프이다.

 

fig, ax = plt.subplots()
ax = tips.plot.box(ax=ax)

 

 

seaborn 라이브러리로 그래프 스타일 정하기

 

1) 그래프에 스타일 적용하기

 

fig, ax = plt.subplots()
ax = sns.violinplot(x='time', y='total_bill', hue='sex', data=tips, split=True)

 

 

2) whitegrid로 스타일을 설정하여 그래프를 그려보자. 그래프의 배경에 줄이 생긴다.

 

sns.set_style('whitegrid')
fig, ax = plt.subplots()
ax = sns.violinplot(x='time', y='total_bill', hue='sex', data=tips, split=True)

 

 

3) 다음은 for문을 이용하여 모든 스타일을 하나씩 적용한 그래프이다.

 

fig = plt.figure()

seaborn_styles = ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks']

for idx, style in enumerate(seaborn_styles):
    plot_position = idx + 1
    with sns.axes_style(style):
        ax = fig.add_subplot(2,3,plot_position)
        violin = sns.violinplot(x='time', y='total_bill', data=tips, ax=ax)
        violin.set_title(style)
        
fig.tight_layout()

 

 

 

출처 : 데이터 분석을 위한 판다스 입문