서문
Drawing attractive figures is important. When making figures for yourself, as you explore a dataset, it’s nice to have plots that are pleasant to look at. Visualizations are also central to communicating quantitative insights to an audience, and in that setting it’s even more necessary to have figures that catch the attention and draw a viewer in.
보기 좋은 그래프를 그리는 것은 중요한 일이다. 나 혼자 데이터를 파악하려고 그래프를 그릴 때도 그 그래프가 보기 좋다면 즐겁다. 데이터의 시각화란 계량화된 인사이트를 보는 사람에게 전달하는 과정이며, 이 때문에 그래프는 집중력을 환기시키고 보는 사람을 더 끌어들이는 요소가 필요하다.
Matplotlib is highly customizable, but it can be hard to know what settings to tweak to achieve an attractive plot. Seaborn comes with a number of customized themes and a high-level interface for controlling the look of matplotlib figures.
Matplotlib가 매우 고도화된 커스터마이징 옵션을 갖고 있긴 하지만, 매력적인 그래프로 만들기 위해 조작법을 배우는 것은 매우 어렵다. Seaborn에서는 이미 커스터마이징 된 테마들이 제공되며, matplotlib를 통해 만들어진 그래프를 조작하는 높은 수준의 인터페이스를 갖고 있다.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
Python
복사
Let’s define a simple function to plot some offset sine waves, which will help us see the different stylistic parameters we can tweak.
몇개의 연속된 사인(사인 코사인 할 때 그 사인) 커브를 그리는 함수를 간단히 정의하고 시작하자. 우리가 다룰 수 있는 스타일 변형 매개변수들과 그에 따른 변화를 보여주는 데에 도움을 줄 것이다.
def sinplot(flip=1):
x = np.linspace(0, 14, 100)
for i in range(1, 7):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
Python
복사
This is what the plot looks like with matplotlib defaults:
위 코드를 통해 정의된 sinplot()은 matplotlib의 기본 옵션에 의해 다음과 같이 나타난다
sinplot()
Python
복사
To switch to seaborn defaults, simply call the set() function.
이를 seaborn의 기본 옵션으로 구현하려면, set() 클래스를 호출하면 된다.
sns.set()
sinplot()
Python
복사
(Note that in versions of seaborn prior to 0.8, set() was called on import. On later versions, it must be explicitly invoked).
(Seaborn의 0.8 버전 이전에서는 set()이 import 메소드로 호출 됐었다. 후 버전부터는 이렇게 추가적으로 호출을 해야한다)
Seaborn splits matplotlib parameters into two independent groups. The first group sets the aesthetic style of the plot, and the second scales various elements of the figure so that it can be easily incorporated into different contexts.
Seaborn에서는 matplotlib의 인자 & 매개변수 입력 용법을 크게 두 종류로 독립해 구분한다. 첫번째 그룹은 장식적인 요소(aesthetic)를 다루는 매개변수 그룹이고, 두 번째는 figure를 구성하는 다양한 요소들의 규모값을 조절해, 다양한 맥락에서 통합된 그래프를 쉽게 만들 수 있도록 하는 그룹이다.
The interface for manipulating these parameters are two pairs of functions. To control the style, use the axes_style() and set_style() functions. To scale the plot, use the plotting_context() and set_context() functions. In both cases, the first function returns a dictionary of parameters and the second sets the matplotlib defaults.
이런 매개변수를 통해 조작하는 방식에도 두 종류의 클래스들이 있다. 외형적 스타일을 설정하기 위해는 axes_style()과 set_style() 기능을 쓰고, 규모값을 설정할 때는 plotting_context()와 set_context() 기능들을 쓴다.
이때 axes_style()과 plotting_context() (각 종류의 첫번째 기능들) 는 dictionary 타입으로 된 매개변수 값을 반환하고, set_style()과 set_context() (각 종류에서 두 번째로 나열된 기능들)는 matplotlib의 기본 옵션들을 조절하는 기능을 한다.
Seaborn figure styles
figure의 스타일에 대해서
There are five preset seaborn themes: darkgrid, whitegrid, dark, white, and ticks. They are each suited to different applications and personal preferences. The default theme is darkgrid. As mentioned above, the grid helps the plot serve as a lookup table for quantitative information, and the white-on grey helps to keep the grid from competing with lines that represent data. The whitegrid theme is similar, but it is better suited to plots with heavy data elements:
Seaborn은 다음과 같은 5개의 테마를 제공한다 : darkgrid, whitegrid, dark, white, ticks. 이런 옵션들은 각기 다른 어플리케이션이나 개인의 취향에 맞게 사용되고 있다. 가장 기본 테마는 darkgird이다. 격자선(grid)은 위에서도 언급했듯 그래프가 담고 있는 정보를 계량화해서 구조적으로 나타나는 것에 이바지하고 있으며, 흰 바탕 위의 회색 격자선은 데이터들이 나타내는 선들과 비교했을 때에도 겹쳐지지 않고 잘 보인다. whitegrid 테마 역시 이와 비슷하지만 복잡하거나 많은 양의 데이터 요소들을 시각화할 때는 whitegrid가 더 어울린다.
(
역주 : white-on grey를 "흰색 위에 회색" 이라고 해석했음)
sns.set_style("whitegrid")
data = np.random.normal(size=(20, 6)) + np.arange(6) / 2
sns.boxplot(data=data);
Python
복사
For many plots, (especially for settings like talks, where you primarily want to use figures to provide impressions of patterns in the data), the grid is less necessary.
격자선(grid)의 필요성이 떨어지는 경우도 물론 많다. (특히, 데이터 속 패턴이 주는 느낌이나 인상에 대해서 우선 언급하는 상황 등..)
sns.set_style("dark")
sinplot()
Python
복사
sns.set_style("white")
sinplot()
Python
복사
Sometimes you might want to give a little extra structure to the plots, which is where ticks come in handy:
간혹 그래프에 조그맣게 추가적인 구성 요소를 주고 싶다면 ticks 를 넣으면 간편하게 이용이 가능하다.
sns.set_style("ticks")
sinplot()
Python
복사
Removing axes spines
그래프 테두리 선(spine) 제거하기
Both the white and ticks styles can benefit from removing the top and right axes spines, which are not needed. The seaborn function despine() can be called to remove them:
white와 ticks 테마를 쓰면 정보 전달 상에서 불필요한 그래프의 윗쪽과 우측 테두리(matplotlib에서는 이를 spine이라고 부른다)를 제거할 수 있다. Seaborn은 despine() 메소드를 통해 테두리를 제거한다.
sinplot()
sns.despine()
Python
복사
Some plots benefit from offsetting the spines away from the data, which can also be done when calling despine(). When the ticks don’t cover the whole range of the axis, the trim parameter will limit the range of the surviving spines.
몇몇 데이터는 테두리 부분(spine)을 떼어놓음으로써 더 효과적으로 데이터를 표현할 수 있는데, 이 역시 despine() 메소드를 통해 구현이 가능하다. ticks가 축에서 표현할 수 있는 전체 범위를 포괄하지 못할 땐, trim 이라는 매개변수 값을 입력해 남아있는 (없어지지 않은) 테두리의 범위를 지정해주면 된다.
f, ax = plt.subplots()
sns.violinplot(data=data)
sns.despine(offset=10, trim=True);
Python
복사
You can also control which spines are removed with additional arguments to despine():
물론 어느 테두리를 제거할지 despine()의 추가적인 인자argument 값 지정을 통해 결정 가능하다.
sns.set_style("whitegrid")
sns.boxplot(data=data, palette="deep")
sns.despine(left=True)
Python
복사
Temporarily setting figure style
임시적으로 스타일 설정하기
Although it’s easy to switch back and forth, you can also use the axes_style() function in a with statement to temporarily set plot parameters. This also allows you to make figures with differently-styled axes:
axes_style() 클래스는 파이썬의 with 문법과 함께 사용하여 임시적으로 그래프의 스타일을 지정해 사용할 수 있다. 이를 통해 그래프를 부분마다 각기 다른 스타일을 적용해 그릴 수 있다.
f = plt.figure(figsize=(6, 6))
gs = f.add_gridspec(2, 2)
with sns.axes_style("darkgrid"):
ax = f.add_subplot(gs[0, 0])
sinplot()
with sns.axes_style("white"):
ax = f.add_subplot(gs[0, 1])
sinplot()
with sns.axes_style("ticks"):
ax = f.add_subplot(gs[1, 0])
sinplot()
with sns.axes_style("whitegrid"):
ax = f.add_subplot(gs[1, 1])
sinplot()
f.tight_layout()
Python
복사
Overriding elements of the seaborn styles
Seaborn 스타일의 오버라이딩 요소
If you want to customize the seaborn styles, you can pass a dictionary of parameters to the rc argument of axes_style() and set_style(). Note that you can only override the parameters that are part of the style definition through this method. (However, the higher-level set() function takes a dictionary of any matplotlib parameters).
Seaborn 스타일을 커스터마이징 할 때, axes_style()과 set_style() 기능의 rc 인자에 dictionary 타입의 매개변수를 지정해 줄 수 있다. 이 방법을 통해야만 매개변수들을 오버라이드(특정 클래스를 우선 적용하는 프로그래밍 기법)할 수 있다는 걸 기억하자. (그러나, 더 높은 단계인 set() 클래스에서는 matplotlib의 모든 매개변수들을 dictionary 타입으로 넣어주면 되긴 한다)
If you want to see what parameters are included, you can just call the function with no arguments, which will return the current settings:
어떤 매개변수들이 포함되어있는지 보고 싶다면, 어떠한 추가 지정 없이 그냥 클래스를 호출하면 된다. 현재의 세팅 값들을 보여 줄 것이다.
sns.axes_style()
Python
복사
{'axes.facecolor': 'white',
'axes.edgecolor': '.8',
'axes.grid': True,
'axes.axisbelow': True,
'axes.labelcolor': '.15',
'figure.facecolor': 'white',
'grid.color': '.8',
'grid.linestyle': '-',
'text.color': '.15',
'xtick.color': '.15',
'ytick.color': '.15',
'xtick.direction': 'out',
'ytick.direction': 'out',
'lines.solid_capstyle': 'round',
'patch.edgecolor': 'w',
'patch.force_edgecolor': True,
'image.cmap': 'rocket',
'font.family': ['sans-serif'],
'font.sans-serif': ['Arial',
'DejaVu Sans',
'Liberation Sans',
'Bitstream Vera Sans',
'sans-serif'],
'xtick.bottom': False,
'xtick.top': False,
'ytick.left': False,
'ytick.right': False,
'axes.spines.left': True,
'axes.spines.bottom': True,
'axes.spines.right': True,
'axes.spines.top': True}
Python
복사
You can then set different versions of these parameters:
다른 버전의 매개변수들도 세팅이 가능하다.
sns.set_style("darkgrid", {"axes.facecolor": ".9"})
sinplot()
Python
복사
Scaling plot elements
그래프의 규모 값을 다루는 요소들
A separate set of parameters control the scale of plot elements, which should let you use the same code to make plots that are suited for use in settings where larger or smaller plots are appropriate.
(앞서 크게 구분했듯) 그래프의 스케일을 조절하는 인자와 매개변수가 있다. 이는 같은 코드를 쓰더라도 출력되는 그래프가 큰 규모가 나을지 더 작은 게 나을지를 따져 알맞게 설정해준다.
First let’s reset the default parameters by calling set():
튜토리얼을 진행해보기 위해 일단 set()을 호출해 기본 세팅으로 리셋해주자
sns.set()
Python
복사
The four preset contexts, in order of relative size, are paper, notebook, talk, and poster. The notebook style is the default, and was used in the plots above.
4개의 미리 설정된 context는 다음과 같다 : paper, notebook, talk, poster 이다. 뒤로 갈수록 규모가 큰 세팅이다. notebook 스타일의 규모가 기본값이며, 지금까지 위에서 다룬 모든 그래프들이 다 해당 사이즈로 출력된 것이다.
sns.set_context("paper")
sinplot()
Python
복사
sns.set_context("talk")
sinplot()
Python
복사
sns.set_context("poster")
sinplot()
Python
복사
Most of what you now know about the style functions should transfer to the context functions.
스타일을 다룬 클래스 파트에서 배운 대부분의 내용이 이번에 배울 클래스에도 적용된다.
You can call set_context() with one of these names to set the parameters, and you can override the parameters by providing a dictionary of parameter values.
위의 4가지 context 중 하나를 set_context() 클래스에 매개변수로 넣어서 세팅을 할 수 있고, 그 세팅 상황에 dictionary 타입의 매개변수를 추가적으로 넣음으로써 오버라이드할 수 있다.
You can also independently scale the size of the font elements when changing the context. (This option is also available through the top-level set() function).
context를 바꾸면서도 폰트의 사이즈는 독립적으로 크기 조절이 가능하다. (이는 가장 상위 레벨의 기능인 set()에서도 적용 가능하다)
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
sinplot()
Python
복사
Similarly, you can temporarily control the scale of figures nested under a with statement.
테마를 임시적으로 설정했던 것과 유사하게, 스케일의 임시적인 적용도 파이썬의 with 문법을 통해 가능하다
Both the style and the context can be quickly configured with the set() function. This function also sets the default color palette, but that will be covered in more detail in the next section of the tutorial.
style과 context 조절은 모두 set() 클래스를 통해 빠르게 통합 적용할 수 있다. 이 클래스는 기본 색상 팔레트를 차용하고 있는데, 다음 튜토리얼 세션에서 이 색 조절에 대해서 더 살펴볼 것이다.