2023. 2. 9. 16:20ㆍ기술 공부/Seaborn
+ Seaborn의 User guide and tutorial를 필사한 내용입니다.
+ 실행 환경은 Anaconda, IPython, Jupyter NoteBook 입니다.
이번에 다룰 주제는,
네 번째 글인 Opinionated defaults and flexible customization 이다.
바로 시작해보자.
이번 글의 제목은 '신중한 기본값 및 유연한 사용자 정의'이다.
Seaborn은 단일 함수 호출로 완전한 그래픽을 생성합니다. 가능한 경우 해당 함수는 플롯의 의미론적 매핑을 설명하는 유익한 축 레이블과 범례를 자동으로 추가합니다.
많은 경우에 seaborn은 데이터의 특성에 따라 매개변수의 기본값을 선택하기도 합니다. 예를 들어 지금까지 살펴본 색상 매핑 은 hue에 할당된 범주형 변수의 다양한 수준을 나타내기 위해 뚜렷한 색조(파란색, 주황색, 때로는 녹색)를 사용했습니다. 숫자 변수를 매핑할 때 일부 함수는 연속 그라데이션으로 전환됩니다.
Seaborn creates complete graphics with a single function call: when possible, its functions will automatically add informative axis labels and legends that explain the semantic mappings in the plot.
In many cases, seaborn will also choose default values for its parameters based on characteristics of the data. For example, the color mappings that we have seen so far used distinct hues (blue, orange, and sometimes green) to represent different levels of the categorical variables assigned to hue. When mapping a numeric variable, some functions will switch to a continuous gradient:
Seaborn은 단 한번의 호출로, 완성된 플롯을 생성한다고 한다.
또한 가능한 경우에는 Seaborn은 플롯의 의미론적 매핑을 설명하는 축 레이블과 범례를 자동으로 추가한다고 한다.
즉, 플롯을 그리면서 데이터 분석을 용이하게 해주는 부가적인 정보를 자동으로 추가한다는 의미인 것 같다.
먼저 사용할 데이터 셋을 불러오자.
penguins = sns.load_dataset('penguins')
penguins
# legend='auto'
sns.relplot(
data=penguins,
x='bill_length_mm',
y='bill_depth_mm',
hue='body_mass_g',
);
'body_mass_g'의 값에 따라 그라데이션으로 색상을 입혀주었다.
그리고, 색상에 대한 범례도 오른쪽에 이쁘게 넣어주었다.
물론, 예제 데이터 셋을 출력해보았을 때, '3750.0' 등 범례에 나와있지 않은 값도 있었으므로,
뭔가 구간화가 되거나, 저 범례는 대략적인 값에 대한 색상 정도만 표현한게 아닐까 추측해보았다.
작업을 공유하거나 게시할 준비가 되면 기본값이 달성하는 것 이상으로 그림을 다듬고 싶을 것입니다. Seaborn은 여러 수준의 사용자 정의를 허용합니다. 모든 그림에 적용되는 여러 내장 테마 를 정의하고, 함수에는 각 플롯의 의미론적 매핑을 수정할 수 있는 표준화된 매개변수가 있으며, 추가 키워드 인수가 기본 matplotlib 아티스트에게 전달되어 훨씬 더 많은 제어가 가능합니다. 플롯을 생성한 후에는 seaborn API를 통해 그리고 미세 조정을 위해 matplotlib 레이어로 드롭 다운하여 해당 속성을 수정할 수 있습니다.
When you’re ready to share or publish your work, you’ll probably want to polish the figure beyond what the defaults achieve. Seaborn allows for several levels of customization. It defines multiple built-in themes that apply to all figures, its functions have standardized parameters that can modify the semantic mappings for each plot, and additional keyword arguments are passed down to the underlying matplotlib artists, allowing even more control. Once you’ve created a plot, its properties can be modified through both the seaborn API and by dropping down to the matplotlib layer for fine-grained tweaking:
설명이 굉장히 길지만, 요약을 하면 굉장히 간단하다.
Seaborn은 matplotlib의 내부 기능을 이용해서 플롯을 이쁘게 꾸밀 수 있다고 한다.
꾸미는 것은 이해하고 난 다음의 일이다. 이 부분에 대해서는 조금 후일로 미루어두자.
한 Cell에 하나씩 코드를 실행하고자, 먼저 백엔드 설정을 해제했다.
(matplotlib의 백엔드를 사용하도록 설정하였다.)
plt.ioff()
Seaborn의 테마 설정 함수를 통해, 테마의 일부를 설정하였다.
sns.set_theme(
style='ticks',
font_scale=1.25
)
플롯을 생성하고 그 객체의 식별자를 grid로 선언하였다.
grid = sns.relplot(
data=penguins,
x='bill_length_mm',
y='bill_depth_mm',
hue='body_mass_g',
palette='crest',
marker='x',
s=100
)
x, y 축의 제목을 설정해주었다.
제목 라벨의 바깥 공백(padding)을 10 주었다.
+ 정확히 내부 공백인지, 외부 공백인지는 모르겠지만 둘 중 하나의 공백을 설정하고 있다.
grid.set_axis_labels('Bill Length (mm)', 'Bill Depth (mm)', labelpad=10)
범례의 제목을 설정해주었다.
grid.legend.set_title('Body Mass (g)')
플롯의 크기를 설정해주었다.
grid.figure.set_size_inches(6.5, 4.5)
플롯의 내부 공백(margin)을 .15로 설정하였다.
grid.ax.margins(.15)
x, y 축의 모양(?)을 설정하였다.
grid.despine(trim=True)
어떻게 완성되었는지 확인해보자.
plt.show()
확실히 정돈되었다는 느낌이 든다.
이렇게, 플롯의 요소 하나하나까지 모두 섬세하게 직접 설정할 수 있다는 것이 Seaborn의 설명이다.
matplotlib와의 관계
Seaborn과 matplotlib의 통합을 통해 노트북의 탐색적 분석, GUI 애플리케이션의 실시간 상호 작용, 여러 래스터 및 벡터 형식의 보관 출력을 포함하여 matplotlib가 지원하는 많은 환경에서 Seaborn을 사용할 수 있습니다.
seaborn 기능만 사용하여 생산성을 높일 수 있지만 그래픽을 완전히 사용자 지정하려면 matplotlib의 개념과 API에 대한 지식이 필요합니다. seaborn의 새로운 사용자를 위한 학습 곡선의 한 측면은 특정 사용자 지정을 달성하기 위해 matplotlib 레이어로 드롭다운이 필요한 때를 아는 것입니다. 반면에 matplotlib에서 오는 사용자는 많은 지식이 이전된다는 것을 알게 될 것입니다.
Matplotlib에는 포괄적이고 강력한 API가 있습니다. 그림의 거의 모든 속성을 원하는 대로 변경할 수 있습니다. seaborn의 높은 수준의 인터페이스와 matplotlib의 깊은 사용자 정의 기능을 결합하면 데이터를 빠르게 탐색하고 출판 품질의 최종 제품에 맞출 수 있는 그래픽을 만들 수 있습니다.
Relationship to matplotlib
Seaborn’s integration with matplotlib allows you to use it across the many environments that matplotlib supports,
including exploratory analysis in notebooks, real-time interaction in GUI applications,
and archival output in a number of raster and vector formats.
While you can be productive using only seaborn functions, full customization of your graphics will require some knowledge of matplotlib’s concepts and API. One aspect of the learning curve for new users of seaborn will be knowing when dropping down to the matplotlib layer is necessary to achieve a particular customization. On the other hand, users coming from matplotlib will find that much of their knowledge transfers.
Matplotlib has a comprehensive and powerful API; just about any attribute of the figure can be changed to your liking. A combination of seaborn’s high-level interface and matplotlib’s deep customizability will allow you both to quickly explore your data and to create graphics that can be tailored into a publication quality final product.
Matplotlib을 사용할 수 있는 환경이라면, 어디서든지 Seaborn을 여러 방면으로 활용할 수 있다고 한다.
또한 Seaborn을 사용하여 빠르게 원하는 데이터 분석 플롯을 생성할 수는 있지만,
이를 완벽하게 제어하고 커스터마이징하기 원한다면 Matplotlib의 개념과 API에 대한 지식이 필요하다고 한다.
그리고 새로 시작하는 Seaborn 사용자에게 찾아오는 특이점 중 하나는
Seaborn을 더 자유롭게 사용하기 위해 Matplotlib에 대해 더 깊게 알아야할 때라고 한다.
마지막으로, Matplotlib을 사용하면 정말 원하는 대로 모든(?) 것을 그릴 수 있다고 한다.
나중에 matplotlib까지 마스터하는 날이 온다면,
matplotlib으로 플롯에 그림 그려보기같은 걸 해보면 재밌을 것 같다.
출처 :
User guide and tutorial — seaborn 0.12.2 documentation
https://seaborn.pydata.org/tutorial/introduction.html#opinionated-defaults-and-flexible-customization
An introduction to seaborn — seaborn 0.12.2 documentation
An introduction to seaborn Seaborn is a library for making statistical graphics in Python. It builds on top of matplotlib and integrates closely with pandas data structures. Seaborn helps you explore and understand your data. Its plotting functions operate
seaborn.pydata.org
GitHub :
MoonsRainbow/seaborn-tutorial
https://github.com/MoonsRainbow/seaborn-tutorial
GitHub - MoonsRainbow/seaborn-tutorial: Seaborn User guide and tutorial 필사 코드입니다.
Seaborn User guide and tutorial 필사 코드입니다. Contribute to MoonsRainbow/seaborn-tutorial development by creating an account on GitHub.
github.com
'기술 공부 > Seaborn' 카테고리의 다른 글
6) Figure-level vs. axes-level functions (1) (0) | 2023.02.12 |
---|---|
5) Similar functions for similar tasks (0) | 2023.02.12 |
3) Multivariate views on complex datasets (0) | 2023.02.09 |
2) A high-level API for statistical graphics (0) | 2023.02.07 |
1) An introduction to seaborn (0) | 2023.02.06 |