🏘️

Building structured multi-plot grids

서문

When exploring medium-dimensional data, a useful approach is to draw multiple instances of the same plot on different subsets of your dataset. This technique is sometimes called either “lattice” or “trellis” plotting, and it is related to the idea of “small multiples”. It allows a viewer to quickly extract a large amount of information about complex data. Matplotlib offers good support for making figures with multiple axes; seaborn builds on top of this to directly link the structure of the plot to the structure of your dataset.
적당한 차원 수를 가진 데이터를 다룰 땐 다음과 같은 접근 방식이 효과적이다 : 크게 보면 같은 갈래의 그래프이지만 변수에 따라 다양히 변화된 여럿의 그래프들을 그리는 방법이 그것이다. 이러한 기법을 "lattice - 일반적인 격자무늬를 뜻함" 혹은 "trellis - 다이아몬드 형태로 기운 꼴을 가진 격자를 뜻함" 그래프라고 부르며, 이건 여러 개의 작은 그래프를 그린다는 개념과 관련이 있다(small multiles 개념).
이건 보는 사람으로 하여금 복잡한 데이터의 많은 정보량을 빨리 뽑아 낼 수 있게 한다. Matplotlib는 이러한 복수 형태의 그래프를 여러 부분에 쉽게 걸쳐 그릴 수 있도록 도와준다. Seaborn은 그러한 matplotlib 기능을 바탕으로 그래프 구조와 데이터셋을 바로 연결해 그래프를 그린다.
( 역주 : trellis는 덩굴이 성장할 수 있게 보조해주는 격자무늬 구조를 일컬는다. 아래 이미지를 보면 이해가 쉽다.)
To use these features, your data has to be in a Pandas DataFrame and it must take the form of what Hadley Whickam calls “tidy” data. In brief, that means your dataframe should be structured such that each column is a variable and each row is an observation.
이러한 특징들을 이용하려면, 이용하려는 데이터셋이 일단 판다스의 데이터프레임 타입이어야 하고, 데이터 과학자인 해들리 위컴이 소위 "깔끔tidy하다"라고 부른 데이터 꼴을 갖춰야 한다. 간단히 말하자면 데이터프레임의 각 칼럼은 변수로 바로 쓸 수 있어야 하고, 각 로우 값이 그 변수의 관찰값으로 구성되어야 한다는 뜻이다.
For advanced use, you can use the objects discussed in this part of the tutorial directly, which will provide maximum flexibility. Some seaborn functions (such as lmplot(), catplot(), and pairplot()) also use them behind the scenes. Unlike other seaborn functions that are “Axes-level” and draw onto specific (possibly already-existing) matplotlib Axes without otherwise manipulating the figure, these higher-level functions create a figure when called and are generally more strict about how it gets set up. In some cases, arguments either to those functions or to the constructor of the class they rely on will provide a different interface attributes like the figure size, as in the case of lmplot() where you can set the height and aspect ratio for each facet rather than the overall size of the figure. Any function that uses one of these objects will always return it after plotting, though, and most of these objects have convenience methods for changing how the plot is drawn, often in a more abstract and easy way.
Seaborn을 좀 더 잘 사용해 보려면, 이번 튜토리얼에서 다룬 내용들이 바로 도움이 될 것이다. 이번에는 다양한 응용성을 최대한으로 끌어 올려 볼 것이다. lmplot(), catplot(), pairplot() 과 같은 Seaborn의 몇몇 클래스들은 티는 나지 않지만 이번에 다룰 내용들을 사용하고 있었다. 이러한 높은 수준의 기능들은 호출되면 시각화한 이미지를 만드는데, 이때 보다 엄격한 세팅을 해줘야 한다. 이와 다르게 "Axes-level function"들은 기존에 존재하는 matplotlib의 Axes 에 별다른 추가 조작 없이 그래프를 그려낸다.
( 역주 : lmplot(), catplot(), pariplot()은 모두 figure-level function이라고 Seaborn 측은 분류하고 있다. 그리고 figure-level을 axes-level 보다 한 단계 높은 수준의 클래스로 취급한다.)
물론 몇몇의 경우엔, 써보고자 하는 클래스들 혹은 그 클래스들이 의존성을 갖는 상위 클래스 구조들에 따라 조금씩은 다른 이용 방식을 제공할 것이다. 마치 lmplot()에서 시각화 이미지의 크기를 조절하고자 할 때 figure에 걸쳐 모든 그래프에 적용하는 게 아닌 각 파셋facets의 그래프를 height와 aspect ratio 매개변수를 써서 조절해주는 것과 같다. 그런 클래스들을 쓸 때면 언제나 그래프를 그리고 난 뒤 다시 적당한 조건을 찾아 재조절해주는 절차를 반복하게 된다. 비록 번거롭지만, 그 클래스들은 그래프를 그리는 방식을 편리하게 바꾸는 기능을 제공하고 있기 때문에 보다 추상적이고 편한 방법으로 이용할 수 있다.
import seaborn as sns import matplotlib.pyplot as plt
Python
복사
sns.set(style="ticks")
Python
복사

Conditional small multiples

조건에 따라 여러개의 작은 그래프들 그리기
The FacetGrid class is useful when you want to visualize the distribution of a variable or the relationship between multiple variables separately within subsets of your dataset. A FacetGrid can be drawn with up to three dimensions: row, col, and hue. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors.
FacetGrid 클래스는 변수의 분포를 시각화하거나, 여러 변수들 사이의 상관관계를 여러개의 그래프로 쪼개서 표현할 때 유용하다. FacetGrid는 칼럼, 로우, hue를 통한 의미구분을 통해 총 3차원까지 시각화가 가능하다. 칼럼과 로우를 사용하는 것은 결과물을 할당해 놓은 axes에 따라 배열하므로 이해하기 쉽다. 3차원 그래프가 깊이(z축)를 추가해서 그리는 것과 같이 hue를 통해 의미구분을 하면 각기 다른 색깔로 구분하면서 단계의 차이를 추가한다.
The class is used by initializing a FacetGrid object with a dataframe and the names of the variables that will form the row, column, or hue dimensions of the grid. These variables should be categorical or discrete, and then the data at each level of the variable will be used for a facet along that axis. For example, say we wanted to examine differences between lunch and dinner in the tips dataset.
해당 클래스는 FacetGrid 객체를 호출하면서 시작된다. 이때 데이터프레임과 각 칼럼과 로우, hue 차원에 적용될 변수의 이름이 함께 기입되어야 한다. 이때 쓸 변수들은 범주형 데이터 혹은 이산형discrete이어야 하고, 그 데이터들은 곧 각 변수의 단계와 할당된 부분에 따라 활용된다. 예를 들어 우리가 tips 데이터 셋에서 점심과 저녁 시간대 사이의 차이를 파악하고자 한다고 쳐보자.
Additionally, each of relplot(), catplot(), and lmplot() use this object internally, and they return the object when they are finished so that it can be used for further tweaking.
덧붙이자면, relplot(), catplot(), lmplot() 은 (figure-level functions) 이런 객체를 내부적으로 쓰고 있고, 계산이 끝나면 이 객체를 반환하기 때문에 axes-level의 객체는 보다 응용해서 구현을 하고 싶을 때 사용된다.
tips = sns.load_dataset("tips")
Python
복사
g = sns.FacetGrid(tips, col="time")
Python
복사
Initializing the grid like this sets up the matplotlib figure and axes, but doesn’t draw anything on them.
FacetGrid를 호출하면 위와 같은 matplotlib의 figure와 axes를 설정한다. 그렇지만 그 위에는 아무것도 그려지지 않는다.
The main approach for visualizing data on this grid is with the FacetGrid.map() method. Provide it with a plotting function and the name(s) of variable(s) in the dataframe to plot. Let’s look at the distribution of tips in each of these subsets, using a histogram.
방금 구축한 그리드grid 위에 데이터 시각화 단계로 들어가는 주된 방법은 FacetGrid.map() 명령어를 쓰는 것이다. 사용할 그래프(클래스) 이름과 데이터프레임에서 시각화를 진행할 변수들의 이름을 기입하자. 예제인 tips 데이터셋에다가 히스토그램으로 각기 time으로 구분된 데이터들의 분포를 파악해보자.
g = sns.FacetGrid(tips, col="time") g.map(plt.hist, "tip");
Python
복사
This function will draw the figure and annotate the axes, hopefully producing a finished plot in one step. To make a relational plot, just pass multiple variable names. You can also provide keyword arguments, which will be passed to the plotting function:
FacetGrid 클래스는 figure에 걸쳐 그래프를 그리고 각 axes에 대한 주석을 달아준다. 잘하면 한번에 완성된 그래프를 그릴 수도 있다. 상관관계에 대한 그래프를 그리고 싶다면 여러 변수들의 이름을 기입하면 된다. 또한 그래프를 그릴 때 필요한 추가적인 옵션 키워드를 추가할 수 있다.
g = sns.FacetGrid(tips, col="sex", hue="smoker") g.map(plt.scatter, "total_bill", "tip", alpha=.7) g.add_legend();
Python
복사
There are several options for controlling the look of the grid that can be passed to the class constructor.
아래 예시는 그리드grid 부분을 어떻게 나타낼지를 조절하는 몇가지 옵션을 사용하는 예시이다. 클래스 인자로 해당 옵션 사항을 기입한다.
g = sns.FacetGrid(tips, row="smoker", col="time", margin_titles=True) g.map(sns.regplot, "size", "total_bill", color=".3", fit_reg=False, x_jitter=.1);
Python
복사
Note that margin_titles isn’t formally supported by the matplotlib API, and may not work well in all cases. In particular, it currently can’t be used with a legend that lies outside of the plot.
margin_titles 는 matplotlib API에서 공식 지원되는 명령어는 아니기에 모든 케이스에서 잘 돌아가진 않을 수 있다는 걸 미리 알아두시길. 특히 지금까지는 그래프 바깥에 위치하는 범례와 함께 쓰는 건 불가능한 상황이다.
The size of the figure is set by providing the height of each facet, along with the aspect ratio:
그래프 이미지 파일의 크기는 각 파셋마다 height와 aspect ratio 를 조절해 줌으로써 설정이 가능하다.
g = sns.FacetGrid(tips, col="day", height=4, aspect=.5) g.map(sns.barplot, "sex", "total_bill");
Python
복사
/Users/mwaskom/code/seaborn/seaborn/axisgrid.py:723: UserWarning: Using the barplot function without specifying order is likely to produce an incorrect plot. warnings.warn(warning)
Plain Text
복사
The default ordering of the facets is derived from the information in the DataFrame. If the variable used to define facets has a categorical type, then the order of the categories is used. Otherwise, the facets will be in the order of appearance of the category levels. It is possible, however, to specify an ordering of any facet dimension with the appropriate *_order parameter:
그래프를 각 파셋에 할당할 때 순서는 데이터프레임을 기반으로 정한다. 만약 파셋에 할당된 변수 데이터가 범주형(위 그래프 예시와 같이 성별 등)으로 사용한다면, 그 범주들에 따라 배열(남&여 배열)된다. 그렇지 않으면 그 범주의 단계에 따라 배열이 결정된다.
( 역주 : 만약 카테고리가 "시각 hour" 등의 범주라면 1,2,3 ... 의 각 레벨에 따라 배열된다는 의미이다)
물론 그와 다르게 *_order 인자와 매개변수 입력을 이용하면 어느 부분에 놓을지 배열하는 것도 구체적으로 조절이 가능하다.
ordered_days = tips.day.value_counts().index g = sns.FacetGrid(tips, row="day", row_order=ordered_days, height=1.7, aspect=4,) g.map(sns.distplot, "total_bill", hist=False, rug=True);
Python
복사
Any seaborn color palette (i.e., something that can be passed to color_palette() can be provided. You can also use a dictionary that maps the names of values in the hue variable to valid matplotlib colors:
모든 Seaborn의 색상 팔레트(color_palette())를 적용할 수 있다. 더불어 dictionary 타입을 이용해 각 변수의 이름과 그 이름에 따라 hue(matplotlib의 색상을 쓸 것)로 의미구분 하도록 매칭시켜 그래프를 그릴 수 있다.
pal = dict(Lunch="seagreen", Dinner="gray") g = sns.FacetGrid(tips, hue="time", palette=pal, height=5) g.map(plt.scatter, "total_bill", "tip", s=50, alpha=.7, linewidth=.5, edgecolor="white") g.add_legend();
Python
복사
You can also let other aspects of the plot vary across levels of the hue variable, which can be helpful for making plots that will be more comprehensible when printed in black-and-white. To do this, pass a dictionary to hue_kws where keys are the names of plotting function keyword arguments and values are lists of keyword values, one for each level of the hue variable.
여기서도 마찬가지로, hue를 통해 변수를 각 단계levels 마다 다른 색이 되도록 조치할 수 있다. 이는 흑백 출력을 했을 때 그래프에 대한 접근성을 높이는 방법이다. 이를 원한다면, hue_kws 인자에다가 dictionary 타입으로 원하는 옵션을 매개변수로 넣어주면 된다. 어떻게 시각화할 것인지 (아래 예제에서는 "marker") 를 dictionary의 key 값으로 삼고, hue를 통한 의미 구분하듯 각 단계마다 어떻게 구분할 것인지는 리스트로 담아(예제에서는 ["^", "v"]) dictionary의 value 값으로 사용하면 된다.
g = sns.FacetGrid(tips, hue="sex", palette="Set1", height=5, hue_kws={"marker": ["^", "v"]}) g.map(plt.scatter, "total_bill", "tip", s=100, linewidth=.5, edgecolor="white") g.add_legend();
Python
복사
If you have many levels of one variable, you can plot it along the columns but “wrap” them so that they span multiple rows. When doing this, you cannot use a row variable.
만약 구분해야 할 단계가 많은 변수를 갖고 있다면, 칼럼 따라 길게 늘어뜨려 그래프를 그리기보단 "wrap" 기법을 통해 여러 행에 걸쳐 그래프를 그릴 수 있다. 이 기법을 쓰면 각 로우에 의미 구분을 둘 수는 없다.
attend = sns.load_dataset("attention").query("subject <= 12") g = sns.FacetGrid(attend, col="subject", col_wrap=4, height=2, ylim=(0, 10)) g.map(sns.pointplot, "solutions", "score", order=[1, 2, 3], color=".3", ci=None);
Python
복사
Once you’ve drawn a plot using FacetGrid.map() (which can be called multiple times), you may want to adjust some aspects of the plot. There are also a number of methods on the FacetGrid object for manipulating the figure at a higher level of abstraction. The most general is FacetGrid.set(), and there are other more specialized methods like FacetGrid.set_axis_labels(), which respects the fact that interior facets do not have axis labels. For example:
FacetGrid.map() 클래스를 통해 그래프를 그릴 때면, 그 그래프의 특정 부분을 조금씩 조절해 보고 싶을 때가 있을 것이다. FacetGrid 객체에 보다 높은 수준의 추상화를 위해 그래프를 조절하는 명령어가 몇 있다. 가장 일반적인게 FacetGrid.set()을 쓰는 것이다. 이보다 더 특화된 방법으로는 FacetGrid.set_axis_labels()와 같이 여러 그래프들을 함께 그리면 그 안에는 축의 값(label)이 표기될 수 없다는 점을 고려하는 명령어들도 있다.
with sns.axes_style("white"): g = sns.FacetGrid(tips, row="sex", col="smoker", margin_titles=True, height=2.5) g.map(plt.scatter, "total_bill", "tip", color="#334488", edgecolor="white", lw=.5); g.set_axis_labels("Total bill (US Dollars)", "Tip"); g.set(xticks=[10, 30, 50], yticks=[2, 6, 10]); g.fig.subplots_adjust(wspace=.02, hspace=.02);
Python
복사
( 역주 : 위 그래프를 살펴보면 xticks=[10, 30, 50], yticks=[2, 6, 10] 를 통해 그래프의 축 값을 미리 지정했다)
For even more customization, you can work directly with the underling matplotlib Figure and Axes objects, which are stored as member attributes at fig and axes (a two-dimensional array), respectively. When making a figure without row or column faceting, you can also use the ax attribute to directly access the single axes.
이보다 더 커스터마이징을 심화시키고 싶다면, 기저에 깔린 matplotlib의 Figure와 Axes 객체 개념들을 바로 이용해 작업하는 게 가능하다. 그 객체란 2차원 상 표현하고자 하는 그래프 부분 부분에 해당하는 요소들이 개별적으로 쌓여있는 것이다. 칼럼이나 로우 부분 부분에 할당하지 않고 그래프를 그릴 때에는, ax 어트리뷰트attribute를 써서 직접 각 axes에 그래프를 할당해 그릴 수 있다.
g = sns.FacetGrid(tips, col="smoker", margin_titles=True, height=4) g.map(plt.scatter, "total_bill", "tip", color="#338844", edgecolor="white", s=50, lw=1) for ax in g.axes.flat: ax.plot((0, 50), (0, .2 * 50), c=".2", ls="--") g.set(xlim=(0, 60), ylim=(0, 14));
Python
복사
( 역주 : for ax in g.axes.flat: for문을 돌려서 여러개의 그래프를 자동으로 그리는 기법을 사용했다)

Using custom functions

커스터마이징 기능 이용하기
You’re not limited to existing matplotlib and seaborn functions when using FacetGrid. However, to work properly, any function you use must follow a few rules:
FacetGrid 기능을 쓰면서 기존의 matplotlib나 seaborn의 기능들을 쓰는 것에 특별한 제약이 있진 않는다. 그렇지만 보다 적절한 작업을 위해서는 어떤 기능을 쓰든 다음과 같은 규칙들을 반드시 지켜야 한다.
1.
It must plot onto the “currently active” matplotlib Axes. This will be true of functions in the matplotlib.pyplot namespace, and you can call matplotlib.pyplot.gca() to get a reference to the current Axes if you want to work directly with its methods.
2.
It must accept the data that it plots in positional arguments. Internally, FacetGrid will pass a Series of data for each of the named positional arguments passed to FacetGrid.map().
3.
It must be able to accept color and label keyword arguments, and, ideally, it will do something useful with them. In most cases, it’s easiest to catch a generic dictionary of **kwargs and pass it along to the underlying plotting function.
1.
반드시 "현재 활성화 된" matplotlib의 Axes 를 기반으로 그래프를 그려야 한다. 이는 matplotlib.pyplot의 namespace 안에서 지켜야 하는 룰이며, 만약 곧바로 작업하길 원한다면 matplotlib.pyplot.gca() 메소드를 호출해 바로 Axes를 만들어 낼 수 있다.
2.
데이터가 위치적으로 적합하게 지정되어야 한다. 내부적으로 FacetGrid는 각각 위치가 지정된 대로 데이터를 Series 타입으로 FacetGrid.map() 기능을 수행토록 설계되었다.
3.
colorlabel 을 지정하는 방식이 적합해야한다. 그래야 이상적으로 각 colorlabel이 제대로 구현될 것이다. 대부분의 경우에는 가장 쉬운 방법으로 기반이 되는 클래스에서 일반적으로 쓰이는 **kwarg 딕셔너리 타입(아스테릭스 가변인자)을 파악해 사용하는 것이다.
Let’s look at minimal example of a function you can plot with. This function will just take a single vector of data for each facet:
가장 간단히 그릴 수 있는 예시를 통해 이해해보자. 아래에서 정의한 함수는 데이터의 단일 벡터를 각 파셋facet에 사용하게끔 되어 있다.
from scipy import stats def quantile_plot(x, **kwargs): qntls, xr = stats.probplot(x, fit=False) plt.scatter(xr, qntls, **kwargs) g = sns.FacetGrid(tips, col="sex", height=4) g.map(quantile_plot, "total_bill");
Python
복사
If we want to make a bivariate plot, you should write the function so that it accepts the x-axis variable first and the y-axis variable second:
만약 이변량bivariate 그래프를 그리고 싶다면, x 축의 변수를 먼저 기입하고 그 다음 y축의 변수를 설정해야 한다.
def qqplot(x, y, **kwargs): _, xr = stats.probplot(x, fit=False) _, yr = stats.probplot(y, fit=False) plt.scatter(xr, yr, **kwargs) g = sns.FacetGrid(tips, col="smoker", height=4) g.map(qqplot, "total_bill", "tip"); # 여기에 x 축 변수와 y 축 변수를 순서대로 적어줬다.
Python
복사
Because matplotlib.pyplot.scatter() accepts color and label keyword arguments and does the right thing with them, we can add a hue facet without any difficulty:
matplotlib.pyplot.scatter()colorlabel을 지정할 수 있고 바로 작업을 해주기 때문에 hue를 추가 지정하는 건 큰 어려움 없이 가능하다.
g = sns.FacetGrid(tips, hue="time", col="sex", height=4) g.map(qqplot, "total_bill", "tip") g.add_legend();
Python
복사
This approach also lets us use additional aesthetics to distinguish the levels of the hue variable, along with keyword arguments that won’t be dependent on the faceting variables:
이러한 방식은 hue를 통한 변수의 단계 구분에 더불어 추가적인 장식적 요소(asthetics)까지 추가해 데이터들을 구분할 수 있다. 모양을 지정하는 건 특정 키워드 인자를 써야하는 건 아니고 임의로 설정할 수 있다.
g = sns.FacetGrid(tips, hue="time", col="sex", height=4, hue_kws={"marker": ["s", "D"]}) g.map(qqplot, "total_bill", "tip", s=40, edgecolor="w") g.add_legend();
Python
복사
Sometimes, though, you’ll want to map a function that doesn’t work the way you expect with the color and label keyword arguments. In this case, you’ll want to explicitly catch them and handle them in the logic of your custom function. For example, this approach will allow use to map matplotlib.pyplot.hexbin(), which otherwise does not play well with the FacetGrid API:
그럼에도 불구하고, 가끔씩은 colorlabel 지정이 기대했던 대로 되지 않을 때가 있을 것이다. 이런 경우엔 다소 유별나더라도 문제점을 파악하고 각 커스터마이징 함수의 로직에 따라 조절해주고 싶을 것이다. 아래 예시는 해당 방법이 아니라면 FacetGrid API에서 잘 작동하지 않는 matplotlib.pyplot.hexbin()를 써본 것이다.
def hexbin(x, y, color, **kwargs): cmap = sns.light_palette(color, as_cmap=True) plt.hexbin(x, y, gridsize=15, cmap=cmap, **kwargs) with sns.axes_style("dark"): g = sns.FacetGrid(tips, hue="time", col="time", height=4) g.map(hexbin, "total_bill", "tip", extent=[0, 50, 0, 10]);
Python
복사

Plotting pairwise data relationships¶

짝 지어진 데이터 간의 관계들을 표현하기
PairGrid also allows you to quickly draw a grid of small subplots using the same plot type to visualize data in each. In a PairGrid, each row and column is assigned to a different variable, so the resulting plot shows each pairwise relationship in the dataset. This style of plot is sometimes called a “scatterplot matrix”, as this is the most common way to show each relationship, but PairGrid is not limited to scatterplots.
PairGrid는 같은 갈래의 그래프이되 각각의 데이터에 맞게 적용된 작은 그래프 여럿을 격자 형태로 배치하고 빠르게 그릴 수 있게 해준다. PairGrid에서는 각 로우와 칼럼에 서로 다른 변수를 배정 해야하며 그 결과물은 배정된 변수 간의 짝 지어진 관계를 표현한다. 아래 예시와 같은 그래프는 종종 "산점도 행렬"이라고도 불리우며 이는 각 관계들을 보여주는 가장 흔한 방식이긴 하지만 PairGrid의 표현 방식이 산점도에만 국한되는 건 아니다.
( 역주 : axes-level의 클래스가 여러개의 그래프를 그릴 때 오와 열을 맞춰 그리므로, 그 그래프들이 행렬처럼 묶여 보이기 때문에 산점도 행렬이라 표현한 듯 하다)
It’s important to understand the differences between a FacetGrid and a PairGrid. In the former, each facet shows the same relationship conditioned on different levels of other variables. In the latter, each plot shows a different relationship (although the upper and lower triangles will have mirrored plots). Using PairGrid can give you a very quick, very high-level summary of interesting relationships in your dataset.
이때 FacetGridPairGrid 간의 차이를 이해하는 게 중요하다. FacetGrid는 변수들의 "단계level"가 달라짐에 따라 같은 상관관계가 어떻게 변화하는지를 보여주는 반면, PairGrid는 다른 변수들끼리 만나 다른 상관관계들을 여럿 표현하는 것이다. (물론 행렬 구조 상 대각선 위 아래의 삼각형 부분 속 그래프들이 서로 대칭된 꼴이긴 하지만)
PairGrid를 쓰면 데이터 셋 속의 상관관계들을 굉장히 빠르고 높은 수준으로 이해할 수 있다.
The basic usage of the class is very similar to FacetGrid. First you initialize the grid, then you pass plotting function to a map method and it will be called on each subplot. There is also a companion function, pairplot() that trades off some flexibility for faster plotting.
PairGrid 클래스의 기초적인 사용법은 FacetGrid와 매우 유사하다. grid를 형성하고, 어떤 그래프를 그릴지 map 메소드를 통해 지정하면 적용될 것이다. 이와 유사한 클래스인 pairplot()도 있다. 다만 이는 PairGrid 만큼 다양하게 응용해서 쓸 순 없을지라도 그만큼 빠르게 그린다는 장점이 있다.
iris = sns.load_dataset("iris") g = sns.PairGrid(iris) g.map(plt.scatter);
Python
복사
A very common way to use this plot colors the observations by a separate categorical variable. For example, the iris dataset has four measurements for each of three different species of iris flowers so you can see how they differ.
이때 이 그래프를 사용하는 가장 대중적인 방법은 관찰값을 범주형 변수에 따라 나눠 색을 달리하는 것이다. 예를 들어, 붓꽃 데이터셋은 각기 3개의 다른 꽃의 종류가 4개의 범주로 구분되어 있으므로, (색 구분을 통해) 이들이 어떻게 달라지는지를 볼 수 있다.
g.map_diag(plt.hist) g.map_offdiag(plt.scatter) g.add_legend();
Python
복사
By default every numeric column in the dataset is used, but you can focus on particular relationships if you want.
기본 옵션 상, 데이터 셋에서 수치형 데이터가 있는 칼럼은 모두 사용되나, 원한다면 특정 상관관계만 골라 볼 수 있다.
g = sns.PairGrid(iris, vars=["sepal_length", "sepal_width"], hue="species") g.map(plt.scatter);
Python
복사
It’s also possible to use a different function in the upper and lower triangles to emphasize different aspects of the relationship.
그래프 행렬 속 대각선을 기준으로 위 삼각형 부분과 아래 삼각형 부분에 각기 다른 그래프를 사용할 수도 있다. 이를 통해 관계의 서로 다른 면까지 강조할 수 있다.
g = sns.PairGrid(iris) g.map_upper(plt.scatter) g.map_lower(sns.kdeplot) g.map_diag(sns.kdeplot, lw=3, legend=False);
Python
복사
The square grid with identity relationships on the diagonal is actually just a special case, and you can plot with different variables in the rows and columns.
(위와 같이) 정사각행렬 꼴로 그래프들이 그려지고 대각선에는 동일한 관계들이 있는 케이스는 사실 자주 쓰이는 스타일은 아니다. PairGrid를 통해 행과 열 부분에 각기 다른 변수들을 원하는대로 집어넣어 그래프를 그릴 수 있으니 참고하자.
g = sns.PairGrid(tips, y_vars=["tip"], x_vars=["total_bill", "size"], height=4) g.map(sns.regplot, color=".3") g.set(ylim=(-1, 11), yticks=[0, 5, 10]);
Python
복사
Of course, the aesthetic attributes are configurable. For instance, you can use a different palette (say, to show an ordering of the hue variable) and pass keyword arguments into the plotting functions.
물론 장식적인 부분도 함께 구성할 수 있다. 예를 들어, (hue를 통한 변수의 구분에다가 순서까지 표현하기 위해서) 각기 다른 색상 팔레트를 매개변수로 직접 지정해주면 된다.
g = sns.PairGrid(tips, hue="size", palette="GnBu_d") g.map(plt.scatter, s=50, edgecolor="white") g.add_legend();
Python
복사
PairGrid is flexible, but to take a quick look at a dataset, it can be easier to use pairplot(). This function uses scatterplots and histograms by default, although a few other kinds will be added (currently, you can also plot regression plots on the off-diagonals and KDEs on the diagonal).
PairGrid는 유연하게 쓸 수 있지만, 데이터 셋을 빠르게 파악하려면 pairplot()을 쓰는 게 더 쉬운 방법이 될 수 있다. 비록 지금은 산점도와 히스토그램을 기본 옵션으로 사용하는 pariplot()이지만 추후에 몇가지 옵션들이 더 추가될 계획이다 (현재까진, 그래프 행렬의 대각선상엔 KDE플롯을, 그 외 구역엔 회귀 그래프까지 그릴 수 있는 수준이다)
sns.pairplot(iris, hue="species", height=2.5);
Python
복사
You can also control the aesthetics of the plot with keyword arguments, and it returns the PairGrid instance for further tweaking.
pairplot()에도 물론 장식적인 요소를 메소드 입력 시 추가함으로써 설정할 수 있다. 그러면 위에서 본 PairGrid 예시와 비슷하되 좀 더 다양한 측면이 부각되도록 그래프를 그린다.
g = sns.pairplot(iris, hue="species", palette="Set2", diag_kind="kde", height=2.5)
Python
복사