본문 바로가기
재미로 하는 코딩

시각화 뽀개기9

by 헬푸밍 2023. 3. 5.

The seaborn.objects interface(seaborn객체 인터페이스)

Customizing the appearance(모양 커스터마이징)

seaborn.objects 인터페이스는 Plot을 통해 matplotlib으로 전환해 matplotlib 기능을 직접사용할 필요성을 줄이면서 심층깊은 커스터마이징을 지원하는 것을 목표한다! 이 목표를 달성하는데 필요한 모든 기능이 구현된 것은 아니니... 조금 기다려야 한다...

 

Parameterizing scales(척도 매개변수화)

모든 데이터 종속적 속상은 Scale 개념과 Plot.scale() 메서드에의해 컨트롤 된다! Plot.scale()메서드는 몇몇 다른 형태의 아규먼트를 받는다. 한 방법은 matplotlib에서 척도를 사용하는 것과 비슷하게 좌표를 변환하는 함수의 이름을 전달하는 것이다.

 

데이터는 diamonds데이터를 사용하고 x에 캐럿, y에 가격을 넣어준 산점도를 그러보자!

(
    so.Plot(diamonds, x="carat", y="price")
    .add(so.Dots())
)

산점도가 위로 휘는 경향이 있어서...

.scale(y='log')로 로그 스케일을 가격에 적용해주면...

diamonds = sns.load_dataset('diamonds')
(
    so.Plot(diamonds, x="carat", y="price")
    .add(so.Dots())
    .scale(y='log')
)

이렇게 y축(가격) 스케일이 바뀌어 그려진다!

 

Plot.scale()은 color와 같은 의미가 있는 속성에 대한 매핑도 조절할 수 있다! seaborn의 함수 인터페이스에서 팔레트 매개변수에 전달할 모든 야규먼트를 직접 전달할 수 있다!

이렇게 .scale(color='flare')을 설정해주면...

(
    so.Plot(diamonds, x="carat", y="price", color="clarity")
    .add(so.Dots())
    .scale(color="flare")
)

flare 컬러가 적용된다!

 

또 하나의 옵션은 (min, max) 튜플 값을 제공하는 건데... 척도가 매핑되어야하는 범위를 조절하는 것이다!  수치 속성과 컬러에 대해 모두 작동한다!

color는 투명도, pointsize를 캐럿으로 하고...

.scale()안에 컬러도 튜플값, 포인트사이즈도 튜플값으로 (min, max)를 넣어주면...

(
    so.Plot(diamonds, x="carat", y="price", color="clarity", pointsize="carat")
    .add(so.Dots())
    .scale(color=("#88c", "#555"), pointsize=(2, 10))
)

투명도 별로 색상이 달라지고... 캐럿별로 점의 크기가 달라진다!

 

추가적인 조절을 위해서 Scale 객체를 전달할 수 있다! 몇몇 다른 유형의 Scale이 있는데, 각각은 적절한 파라미터를 가지고 있다. 예를 들면, Continuous는 입력 도메인(norm), 출력 범위(values), 둘을 매핑하는 함수(trans)를 사용할 수 있는 반면에, Nomial은 순서를 명시하게 해준다!

value='crest', norm=(0, 3), trans='sqrt'를 Continuous에 넣은 뒤 color에 넣어주고...

Nomnial에는 ['o', '+', 'x']를 넣어주고 order는 ['Ideal', 'Preminum', 'Good']으로 지정해준 뒤 marker에 넣어주면... 

(
    so.Plot(diamonds, x="carat", y="price", color="carat", marker="cut")
    .add(so.Dots())
    .scale(
        color=so.Continuous(values="crest", norm=(0, 3), trans="sqrt"),
        marker=so.Nominal(["o", "+", "x"], order=["Ideal", "Premium", "Good"]),
    )
)

carat별(0, 1, 2, 3) cut별(Ideal, Premium, Good) 가격이 이렇게 그려진다...

trans='sqrt'(제곱근)가 하는 일은 색상을 오른쪽에 치우치게(빠르게 진해지도록) 하는 듯 하다...

crest 팔레트를 확인해 보면...

sns.palplot(sns.color_palette('crest'))

이런데 그래프에서는 오른쪽에 치우치게(색상이 금방 진해지도록) 그려졌고...

 

trans='pow'(제곱)로 그려보면...

(
    so.Plot(diamonds, x="carat", y="price", color="carat", marker="cut")
    .add(so.Dots())
    .scale(
        color=so.Continuous(values="crest", norm=(0, 3), trans='pow'),
        marker=so.Nominal(["o", "+", "x"], order=["Ideal", "Premium", "Good"]),
    )
)

색상이 왼쪽으로 치우치게(느리게 진해지도록) 그려졌다!

 

Customizing legends and ticks(범레와 눈금 커스터마이징)

Scale 객체는 값이 어떤 값이 눈금 레이블로/ 범례 안에서 나타나야 하는지, 어떤 방식으로 나타나는지 명시하는 방법이다! 예를들면, Continuous.tick() 메서드는 눈금의 밀도나 위치를 조정하게 해주고, Continuous.label 메서드는 형식을 수정하게 해준다!

x에 so.Continuous.thick(every=0.5)으로 눈금이 0.5마다 그려지게 하고...

y에 so.Continuous.label(like='${x:.0f}')로 소수점 없는 달러 형식으로 그려지게 하고...

color에 so.Continuous().tick(at=[1, 2, 3, 4])로 범례가 1,2,3,4캐럿만 있게 하면...

(
    so.Plot(diamonds, x="carat", y="price", color="carat")
    .add(so.Dots())
    .scale(
        x=so.Continuous().tick(every=0.5),
        y=so.Continuous().label(like="${x:.0f}"),
        color=so.Continuous().tick(at=[1, 2, 3, 4]),
    )
)

이렇게 명령한 것과 같이 그려진다!

Customizing limits, labels, and titles(제한, 레이블, 제목 커스터마이징)

Plot은 Plot.label(), Plot.limit(), Plot.share()을 포함하여 간단한 커스터마이징을 위한 많은 메서드가 있다!

펭귄 데이터를 이용해서...

x에 몸무게, y에 종, color에 섬...

성별로 서브플롯을 지정해 산점도를 그릴건데...

.share(x=False)로 x축을 따로 그려주고...

.limit(y=(2.5, -.5))으로 y 범위를 조정해주고?(정확히는 모르겠다...)

.label(
    x="Body mass (g)", y="",
    color=str.capitalize,
    title="{} penguins".format,
)로 x축 레이블을 Body mass (g)으로 지정해 주고, y축 레이블은 없게 하고...

범례 제목을 첫글자 대문자로 바꿔주고...

제목은 Male penguins, Female penguins가 나오게 해주면...

(
    so.Plot(penguins, x="body_mass_g", y="species", color="island")
    .facet(col="sex")
    .add(so.Dot(), so.Jitter(.5))
    .share(x=False)
    .limit(y=(2.5, -.5))
    .label(
        x="Body mass (g)", y="",
        color=str.capitalize,
        title="{} penguins".format,
    )
)

이렇게 그려진다...

 

Theme customization(테마 커스터마이징)

마지막으로, Plot은 Plot.theme 메서드로 데이터 독립적인 테마를 지원한다. 현재, Plot.theme 메서드는 matplotlib rc 파라미터의 딕셔너리를 받는다. 직접 설정하거나 seaborn의 테마 함수로부터 파라미터 패키지를 넘겨줄 수 있다!

seaborn의 axes_style을 import 해주고...

Plot.theme 메서드에 축 스타일을 whitegrid로 해주고... 라인스타일을 :로 해주면...

from seaborn import axes_style
so.Plot().theme({**axes_style("whitegrid"), "grid.linestyle": ":"})

이렇게 플롯의 테마를 설정할 수 있다!


참고사이트

https://seaborn.pydata.org/tutorial/objects_interface.html#customizing-the-appearance

 

The seaborn.objects interface — seaborn 0.12.2 documentation

The seaborn.objects interface The seaborn.objects namespace was introduced in version 0.12 as a completely new interface for making seaborn plots. It offers a more consistent and flexible API, comprising a collection of composable classes for transforming

seaborn.pydata.org

 

'재미로 하는 코딩' 카테고리의 다른 글

다이아몬드 가격 예측해보기  (4) 2023.03.19
시각화 뽀개기10  (0) 2023.03.16
태블로를 사용한 스타벅스 매장정보 대시보드  (0) 2023.03.05
시각화 뽀개기9  (0) 2023.03.04
시각화 뽀개기8  (0) 2023.03.02

댓글