🎨

Choosing color palettes

서문

Color is more important than other aspects of figure style because color can reveal patterns in the data if used effectively or hide those patterns if used poorly. There are a number of great resources to learn about good techniques for using color in visualizations, I am partial to this series of blog posts from Rob Simmon and this more technical paper. The matplotlib docs also now have a nice tutorial that illustrates some of the perceptual properties of the built in colormaps.
그래프에 있어서 색상 활용은 여타 장식적인 요소보다 훨씬 중요하다. 색상은 효과적으로 사용했을 때 데이터의 패턴을 잘 보여줄 수 있기 때문이다. 색깔로 시각화를 하는 좋은 테크닉을 배울 자료들은 시중에도 많으며, 이번 튜토리얼 시리즈는 Rob Simmon의 블로그 포스팅링크 ← 이곳의 기술 문서를 참고했다. matplotlib의 도큐먼트 역시 컬러맵 개념에 대해서 파악해 나가는데에 훌륭한 튜토리얼을 갖고 있다.
Seaborn makes it easy to select and use color palettes that are suited to the kind of data you are working with and the goals you have in visualizing it.
Seaborn은 다루고 있는 데이터 혹은 시각화하려는 목표에 적합한 컬러 팔레트(color palette)를 쉽게 선택하고 사용할 수 있도록 해준다.
import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set()
Python

Building color palettes

컬러 팔레트 구
The most important function for working with discrete color palettes is color_palette(). This function provides an interface to many (though not all) of the possible ways you can generate colors in seaborn, and it’s used internally by any function that has a palette argument (and in some cases for a color argument when multiple colors are needed).
디스크리트discrete 컬러 팔레트를 이용할 때 가장 중요한 클래스는 color_palette()이다.
( 역주 : discrete는 "별개의" 라는 뜻을 가졌으며, 문맥상 아래와 같은 "서로 다른" 색깔들로 구성된 컬러 팔레트를 지칭한다.
다만 별개 팔레트, 구분 팔레트 등으로 번역하면 어색하므로 "디스크리트discrete 컬러 팔레트"라는 단어로 번역함을 이해해주시길. 이와 반대되는 개념의 팔레트는 시퀀셜sequential 팔레트로, 색깔들의 구성이 서로 연관성이 있다. 한 가지 색이 점차 변해가는 팔레트가 대표적으로, 튜토리얼 하단부에서 배우게 된다.)
이 클래스는 Seaborn 안에서 원하는 색을 많이 만들 수 있도록 (물론 모든 걸 만들 순 없지만) 가능성을 열어두었다. 그리고 이는 palette 라는 인자argument를 갖는 모든 클래스들에게 적용될 수 있다. (가끔씩은 color 인자를 통해 여러 개의 색상 지정이 필요한 경우도 있다)
color_palette() will accept the name of any seaborn palette or matplotlib colormap (except jet, which you should never use). It can also take a list of colors specified in any valid matplotlib format (RGB tuples, hex color codes, or HTML color names). The return value is always a list of RGB tuples.
color_palette()는 Seaborn의 팔레트나 matplotlib의 컬러맵이라면 전부 사용이 가능할 것이다 (우리가 쓸 일 없는 jet은 예외로 한다). color_palette()에는 matplotlib에서 사용되는 적합한 포맷(RGB 값을 담은 tuples, hex color codes, HTML에서 쓰이는 색상 코드)을 리스트 타입에 담아서 사용한다. 이때 결과물은 늘 RGB 튜플을 담은 리스트로 반환된다.
Finally, calling color_palette() with no arguments will return the current default color cycle.
마지막으로, color_palette()를 아무런 추가적인 인자 없이 호출하면 그 타이밍에 설정되어 있는 기본 옵션의 컬러 싸이클이 적용된다.
( 역주 : color_palette() 클래스를 호출하면 아래와 같이 RGB값 튜플 10개가 리스트로 나온다. 컬러 싸이클이란 이를 지칭하는 것인듯 하다)
A corresponding function, set_palette(), takes the same arguments and will set the default color cycle for all plots. You can also use color_palette() in a with statement to temporarily change the default palette (see below).
이와 대응되는 클래스인 set_palette()color_palette()와 같은 인자argument를 쓰고, 호출하면 모든 그래프들에 대해서 기본 옵션으로 컬러 싸이클을 세팅한다 (세팅 초기화). 일시적으로 다른 색상 팔레트를 기본 팔레트 대신 사용하고 싶을 땐 파이썬 with 구문으로 color_palette() 를 호출할 수도 있다 (밑에서 예시로 설명하겠다)
It is generally not possible to know what kind of color palette or colormap is best for a set of data without knowing about the characteristics of the data. Following that, we’ll break up the different ways to use color_palette() and other seaborn palette functions by the three general kinds of color palettes: qualitative, sequential, and diverging.
데이터의 구체적인 특징들을 알지 못한 채, 그 데이터에 어떤 색상 팔레트나 컬러맵이 어울릴지 판단하는 건 일반적으로 불가능한 일이다. 그렇기에 color_palette()와 다른 Seaborn의 팔레트 클래스들을 다음과 같은 3가지 방식으로 적용하는 방법에 대해서 알아보고자 한다. 정성적qualitative 방법, 시퀀셜sequentail 방법, 다이버징diverging 방법 3가지이다.
( 역주 : sequential과 diverging은 마땅한 번역어가 없어 그대로 음차해 사용했다)

Qualitative color palettes¶

컬러 팔레트의 정성적 적용법
Qualitative (or categorical) palettes are best when you want to distinguish discrete chunks of data that do not have an inherent ordering.
정성적qualitative 혹은 범주형categorical 팔레트는 따로 따로 분리된 데이터를 구분할 때 가장 좋은 팔레트이다. 그 데이터란 내부적으로 위계가 없는 범주 구분들이 있는 데이터를 말한다.
( 역주 : 내부적으로 위계가 없는 범주 구분이란, 바로 아래 팔레트 예제처럼 색깔이 구분되었으나, 그 색 배열에는 우열성, 위계성이 없는 그러한 구분을 의미한다)
When importing seaborn, the default color cycle is changed to a set of ten colors that evoke the standard matplotlib color cycle while aiming to be a bit more pleasing to look at.
Seaborn을 호출하면 기본 컬러 싸이클 옵션은 matplotlib의 표준 컬러 싸이클의 색으로 구성된 10종 컬러 싸이클이다. 다만 그 표준 컬러를 조금 더 보기 좋은 색상으로 바꿔 놓긴 했다.
current_palette = sns.color_palette() sns.palplot(current_palette)
Python
There are six variations of the default theme, called deep, muted, pastel, bright, dark, and colorblind.
여기엔 기본 테마를 변형한 6개의 옵션도 있다. deep, muted, pastel, bright, dark, colorblind

Using circular color systems¶

컬러 사이클 시스템 이용하기
When you have an arbitrary number of categories to distinguish without emphasizing any one, the easiest approach is to draw evenly-spaced colors in a circular color space (one where the hue changes while keeping the brightness and saturation constant). This is what most seaborn functions default to when they need to use more colors than are currently set in the default color cycle.
n개의 범주로 구분된 데이터가 있되, 딱히 한 부분만을 강조하지 않으면서 데이터 전체를 효과적으로 구분하는 가장 쉬운 방법은 다음과 같다. 원형으로 된 도형 안에 균등하게 색을 배치하는 것이다.
(밝기나 농도는 그대로 유지한 채 색상만 바꾸는 것이다. 왜냐하면 색이 완전히 바뀌는 게 아니라 채도 등이 조금씩 바뀌면 위계를 나타내는 것처럼 보이기 때문이다)
이게 대부분의 Seaborn 클래스들이 많은 종류의 색을 써서 구분해야 할 때 기본 옵션으로 쓰는 방식이다.
The most common way to do this uses the hls color space, which is a simple transformation of RGB values.
이를 써보기 위한 가장 대중적인 방법은 hls 매개변수를 이용하는 것이다. hls는 RGB 값을 간단히 바꿔준 것이다.
sns.palplot(sns.color_palette("hls", 8))
Python
There is also the hls_palette() function that lets you control the lightness and saturation of the colors.
hls_palette() 클래스를 이용하여 위 팔레트의 밝기나 채도를 조절할 수 있다.
sns.palplot(sns.hls_palette(8, l=.3, s=.8))
Python
However, because of the way the human visual system works, colors that are even “intensity” in terms of their RGB levels won’t necessarily look equally intense. We perceive yellows and greens as relatively brighter and blues as relatively darker, which can be a problem when aiming for uniformity with the hls system.
그러나 인간의 시각 체계 때문에, RGB 값에 따라 서로 다른 색이 똑같은 빛의 강도를 갖고 있어도 그걸 수용할 때 똑같다고 인식하지 않는다. 인간은 노란 색과 녹색을 상대적으로 밝게 인식하고 파랑색은 상대적으로 어둡게 인식한다. 이는 hls 시스템을 이용해 통일감 있게 색채 구성 하려 할 때 방해요소가 된다.
To remedy this, seaborn provides an interface to the husl system (since renamed to HSLuv), which also makes it easy to select evenly spaced hues while keeping the apparent brightness and saturation much more uniform.
이를 극복하기 위해, Seaborn은 husl 시스템을 제공한다. 제각각의 색으로 구분 된 팔레트에서 색을 고를 때, 그것들의 밝기와 채도가 고르게 구성되어 색상 선택을 훨씬 쉽게 만들어 준다. (요즘엔 HSLuv라고 불리는 개념이다)
sns.palplot(sns.color_palette("husl", 8))
Python
There is similarly a function called husl_palette() that provides a more flexible interface to this system.
그와 유사한 성질을 가진 husl_palett() 클래스를 써서 이런 시스템을 응용해 사용할 수 있다.

Using categorical Color Brewer palettes¶

컬러 브루어 팔레트를 이용해 범주 구분하기
Another source of visually pleasing categorical palettes comes from the Color Brewer tool (which also has sequential and diverging palettes, as we’ll see below). These also exist as matplotlib colormaps, but they are not handled properly. In seaborn, when you ask for a qualitative Color Brewer palette, you’ll always get the discrete colors, but this means that at a certain point they will begin to cycle.
또 다른 방법으로 데이터 범주를 예쁘게 구분 지을 수 있는데, 컬러 브루어(Color Brewer) 도구를 쓰는 것이다.
(이 방법은 앞서 언급한 정성적qualitative 방법 외에도 시퀀셜과 다이버징 방법 모두를 통해 진행될 수도 있다. 뒤에 예시를 통해 파악해 볼 것이다)
matplotlib의 컬러맵이 이미 존재하긴 하지만, 그들을 일일이 적합하게 다루는 건 어려운 일이다. Seaborn을 통해 범주 구분을 위한 컬러 브루어 팔레트를 사용할 때, 디스크리트discrete한 색상들을 얻을 수 있다. 그러나 이는 어느 순간 구분하는 색상이 돌고 돌 수 있다는 걸 의미한다.
( 역주 : 서로 관련성 없는 디스크리트discrete한 색상으로 팔레트를 구성한다고 생각해보자. 너무 많은 색들이 사용되다 보면 어느 순간부터 쓸 색깔이 다 떨어진다)
A nice feature of the Color Brewer website is that it provides some guidance on which palettes are color blind safe. There is a variety of kinds of color blindness, but the most common variant leads to difficulty distinguishing reds and greens. It’s generally a good idea to avoid using red and green for plot elements that need to be discriminated based on color. This comparison can be helpful to understand how the the seaborn color palettes perform for different type of colorblindess.
컬러 브루어 웹사이트의 장점 중 하나는 특정 색상에 대해서 색맹을 가진 사람까지도 고려한 가이드를 제공한다는 점이다. 세상에는 다양한 종류의 색맹이 존재하지만, 가장 자주 발견되는 색맹은 빨강과 초록을 구분할 수 없는 색맹이다. 따라서 적색과 녹색을 기반으로 데이터를 구분하는 걸 피하는 게 좋은 아이디어가 될 수 있다. 링크를 통해 확인할 수 있는 각종 비교들은 Seaborn이 각종 색맹 종류를 위해 어떻게 색상 팔레트를 사용하고 있는지 파악하는데 도움이 될 것이다.
sns.palplot(sns.color_palette("Paired"))
Python
sns.palplot(sns.color_palette("Set2"))
Python
To help you choose palettes from the Color Brewer library, there is the choose_colorbrewer_palette() function. This function, which must be used in a Jupyter notebook, will launch an interactive widget that lets you browse the various options and tweak their parameters.
컬러 브루어 라이브러리를 통해 색상 선택하는 걸 도와주는 choose_colorbrewer_palette() 클래스도 있다. 주피터 노트북에서만 사용할 수 있는 기능이며, 다양한 옵션을 찾아 볼 수 있으며 각각의 매개변수를 조율할 수 있도록 인터렉티브 위젯을 화면에 띄워 주는 기능이다.
Of course, you might just want to use a set of colors you particularly like together. Because color_palette() accepts a list of colors, this is easy to do.
물론 자신이 좋아하는 색깔들로만 세트를 만들어 사용하고 싶을 때도 있을 것이다. color_palette()가 색깔을 담은 리스트 타입을 인자로 쓸 수 있으므로 쓰고자 하는 색들을 리스트 타입으로 저장해두면 쉽게 사용이 가능하다.
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"] sns.palplot(sns.color_palette(flatui))
Python

Using named colors from the xkcd color survey

xkcd 색상 명칭을 바탕으로 색상을 선택하기
A while back, xkcd ran a crowdsourced effort to name random RGB colors. This produced a set of 954 named colors, which you can now reference in seaborn using the xkcd_rgb dictionary:
예전에 xkcd 웹사이트에서 임의의 RGB 색상에 대해 설문조사를 진행해 많은 사람들이 그 색에 대한 이름 짓기를 했었다. 이를 통해 954가지 색에 대한 별명이 붙었으며, 이를 Seaborn에서도 차용했다. xkcd_rgb 딕셔너리 타입으로 색상을 지정해 사용할 수 있다.
( 역주 : xkcd 라는 만화를 연재하던 랜들 먼로라는 사람은 남자와 여자가 색상을 다르게 인지한다는 관념을 검증 해보기 위해 위와 같이 성별에 따른 이름 짓기 설문을 진행했다. 비록 성별 간의 유의미한 차이를 발견하지 못했으나 그때 명명된 이름들이 아직도 xkcd 코드라는 개념으로 사용 되고 있다.)
plt.plot([0, 1], [0, 1], sns.xkcd_rgb["pale red"], lw=3) plt.plot([0, 1], [0, 2], sns.xkcd_rgb["medium green"], lw=3) plt.plot([0, 1], [0, 3], sns.xkcd_rgb["denim blue"], lw=3);
Python
In addition to pulling out single colors from the xkcd_rgb dictionary, you can also pass a list of names to the xkcd_palette() function.
xkcd_rgb 딕셔너리에서 색상 하나씩을 빼내어 쓰고 싶다면, 딕셔너리의 키key값 (xkcd 별명) 을 리스트에 담아 xkcd_palette()에 인자로써 넣어주면 된다.
colors = ["windows blue", "amber", "greyish", "faded green", "dusty purple"] sns.palplot(sns.xkcd_palette(colors))
Python

Sequential color palettes¶

시퀀셜 컬러 팔레트
The second major class of color palettes is called “sequential”. This kind of color mapping is appropriate when data range from relatively low or uninteresting values to relatively high or interesting values. Although there are cases where you will want discrete colors in a sequential palette, it’s more common to use them as a colormap in functions like kdeplot() and heatmap() (along with similar matplotlib functions).
컬러 팔레트를 사용하는 두 번째 큰 방법론인 시퀀셜sequential 적용법에 대해서 알아보자. 이러한 색상 적용법은 데이터가 낮은 값에서 높은 값으로, 혹은 중요도가 떨어지는 값에서 올라가는 값 등으로 이어지는 범위를 가질 때 적합한 방법이다. 물론 순차적으로(sequential) 구분될 수 있는 데이터를 굳이 딱딱 구분되는 색(디스크리트 팔레트를 말하는 것이다)으로 표현하고 싶을 수도 있겠지만, kdeplot()이나 heatmap()처럼 부드럽게 이어져 구분되는 시퀀셜 컬러 팔레트를 쓰는 게 더 대중적이라는 걸 기억하자. (matplotlib의 기능들도 이와 비슷하다)
( 역주 : 아래 두 개의 팔레트를 보면서 디스크리트 팔레트와 시퀀셜 팔레트 간의 차이를 살펴보면 이해에 도움이 될 것이다)
디스크리트 팔레트
시퀀셜 팔레트
It’s common to see colormaps like jet (or other rainbow palettes) used in this case, because the range of hues gives the impression of providing additional information about the data. However, colormaps with large hue shifts tend to introduce discontinuities that don’t exist in the data, and our visual system isn’t able to naturally map the rainbow to quantitative distinctions like “high” or “low”. The result is that these visualizations end up being more like a puzzle, and they obscure patterns in the data rather than revealing them. The jet colormap is misleading because the brightest colors, yellow and cyan, are used for intermediate data values. This has the effect of emphasizing uninteresting (and arbitrary) values while deemphasizing the extremes.
그냥 랜덤한 색을 써서 구분하고자 할 땐 jet (혹은 다른 무지개 색 팔레트)와 같은 컬러맵을 쓰는 게 더 흔한 현상이다. 그 이유는 순차적sequential으로 색이 변해가는 구분을 쓰면 그 데이터를 표현함에 있어 (위계와 같은) 추가적인 정보가 포함되기 때문이다. 그러나 jet 팔레트와 같이 알록달록하게 여러 색으로 변해가는 팔레트를 써서 데이터를 구분하면 이를 받아들일 때 데이터가 규칙적이지 않고 분절 된다는 느낌을 준다. (실제로는 규칙적으로 위계가 표현되고 있음에도)
( 역주 : jet 컬러 팔레트란 아래 이미지처럼 생긴 컬러 팔레트를 말한다. 마치 시퀀셜 팔레트처럼 채도가 조금씩 변해가지만 (파랑 → 하늘색), 전체적으로 보면 파랑 → 하늘 → 노랑 등으로 채도 변화에 따른 규칙성은 없다.
만약 빨주노초파남보 무지개 색으로 컬러 팔레트가 구성되고, 높은 값을 가진 데이터 순으로 빨(1)주(2)노(3)초(4)파(5)남(6)보(7) 색이 부여된다고 가정해 보자. 데이터가 3에서 5로 변했을 때 컬러는 노란색 → 초록색 → 파란색으로 변해가지만 사실 노란색과 초록색 간에, 초록색과 파란색 간에 연관성이 없이 때문에 (서로 보색일 수도 있는 것이고) 이를 받아들일 때 규칙성이 없다고 시각 체계는 오해하게 된다.
그 결과 시각화는 더 이상 직관적이지 않고 퍼즐처럼 헷갈리게 되며, 기존의 데이터가 갖고 있던 패턴을 밝혀주기는커녕 더 패턴을 모호하게 만들어 버린다. jet 컬러맵은 가장 밝은 색인 노랑과 빨강이 가장 높은 값을 표현하는 게 아니라 중간 정도의 값을 표현하기 때문에 이렇게 오해를 자아낼 수 있는 것이다. 오히려 주요 관심사 값이 아닌데도 극단값처럼 오해를 사면서 그 값이 시각적으로 강조되는 문제가 생길 수 있다.
For sequential data, it’s better to use palettes that have at most a relatively subtle shift in hue accompanied by a large shift in brightness and saturation. This approach will naturally draw the eye to the relatively important parts of the data.
따라서 순차적인 위계를 가진 데이터에서는 기껏해야 밝기와 채도가 조금씩 미묘하게 변해가는 색상으로만 구분하는 것이 더 좋다. 이러한 방법이 데이터의 중요한 부분에 우리 눈을 집중시키는 데에 도움이 될 것이다.
The Color Brewer library has a great set of these palettes. They’re named after the dominant color (or colors) in the palette.
Color Brewer 라이브러리는 이를 위한 훌륭한 팔레트 세트를 제공하고 있다. 팔레트는 메인 색상에 따라 이름 지어졌다.
sns.palplot(sns.color_palette("Blues"))
Python
Like in matplotlib, if you want the lightness ramp to be reversed, you can add a _r suffix to the palette name.
matplotlib와 마찬가지로 순서를 거꾸로 (점점 어둡게가 아닌 점점 밝게 등) 배치하고 싶다면 _r 을 팔레트 이름 뒤에 추가적으로 붙여서 사용하면 된다.
sns.palplot(sns.color_palette("BuGn_r"))
Python
Seaborn also adds a trick that allows you to create “dark” palettes, which do not have as wide a dynamic range. This can be useful if you want to map lines or points sequentially, as brighter-colored lines might otherwise be hard to distinguish.
Seaborn은 어두운 색 팔레트를 만들기 위한 추가 기법도 사용이 가능하다. 밝은 색상은 어두운 색들에 비해 경계를 구분하기가 어려우므로 컬러맵의 라인이나 점들의 색을 부드럽게 이어 구분하고 있을 때 이 매개변수가 유용하다.
sns.palplot(sns.color_palette("GnBu_d"))
Python
Remember that you may want to use the choose_colorbrewer_palette() function to play with the various options, and you can set the as_cmap argument to True if you want the return value to be a colormap object that you can pass to seaborn or matplotlib functions.
choose_colorbrewer_palette()를 다양한 옵션들과 함께 사용하고자 한다면, as_cmap = True 로 인자 값을 설정해야 한다는 걸 기억하자. 이렇게 하면 반환되는 값이 컬러맵 객체가 되고 이를 통해 seaborn이나 matplotlib 클래스에 바로 사용할 수 있다.

Sequential “cubehelix” palettes¶

시퀀셜 큐브헬릭스 팔레트
The cubehelix color palette system makes sequential palettes with a linear increase or decrease in brightness and some variation in hue. This means that the information in your colormap will be preserved when converted to black and white (for printing) or when viewed by a colorblind individual.
큐브헬릭스 색상 팔레트 시스템은 점진적으로 증가 혹은 감소하는 시퀀셜 팔레트를 지칭한다. 이때 그 증감은 밝기일 수도 있고 다른 색깔 옵션(채도, 명도 등)이 될 수도 있다. 그 말인 즉슨, 이 큐브헬릭스 컬러맵은 흑백 출력을 하거나 특정 색에 대한 색맹이 있는 사람이 봐도 그 컬러맵이 가진 의미 구분 정보는 유지된다는 뜻이다.
Matplotlib has the default cubehelix version built into it:
Matplotlib는 큐브헬릭스 버전에 대해서 다음과 같은 기본 옵션을 갖고 있다
sns.palplot(sns.color_palette("cubehelix", 8))
Python
Seaborn adds an interface to the cubehelix system so that you can make a variety of palettes that all have a well-behaved linear brightness ramp.
Seaborn은 이런 큐브헬릭스 시스템에 여러가지 다양한 옵션을 추가해서, 밝기가 점차 변화해가는 라인 모양의 팔레트를 만들 수 있게 설계했다.
The default palette returned by the seaborn cubehelix_palette() function is a bit different from the matplotlib default in that it does not rotate as far around the hue wheel or cover as wide a range of intensities. It also reverses the order so that more important values are darker:
seaborn의 cubehelix_palette()를 통해 만들어지는 기본 팔레트는 matplotlib의 기본 큐브헬릭스와 조금 다르게 생겼다. 바퀴형식으로 생기지도 않았으며 다양한 범위의 색상 강도를 표현하지도 않는다. 다만 색상의 변화를 거꾸로 배치해서 중요한 값일수록 어둡게 만들 수 있다.
sns.palplot(sns.cubehelix_palette(8))
Python
Other arguments to cubehelix_palette() control how the palette looks. The two main things you’ll change are the start (a value between 0 and 3) and rot, or number of rotations (an arbitrary value, but probably within -1 and 1),
cubehelix_palette()의 표현 방식을 조절하는 다른 인자들도 있다. 그 중 메인 요소인 두 가지는 바로 startrot 값이다. (start는 0과 3 사이의 값으로 구성되고 rot은 임의의 값으로 구성하되 -1과 1 사이로 대개 설정된다)
( 역주 : rot은 rotation의 축약 표현이다)
sns.palplot(sns.cubehelix_palette(8, start=.5, rot=-.75))
Python
You can also control how dark and light the endpoints are and even reverse the ramp:
양 끝 포인트의 밝기 또한 조절할 수 있으며, 팔레트를 뒤집을 수도 있다.
sns.palplot(sns.cubehelix_palette(8, start=2, rot=0, dark=0, light=.95, reverse=True))
Python
By default you just get a list of colors, like any other seaborn palette, but you can also return the palette as a colormap object that can be passed to seaborn or matplotlib functions using as_cmap=True.
여타 Seaborn의 팔레트와 같은 컬러 조합 리스트 하나를 간단히 생성해 두는 것이 가능하다. 이때 그 생성한 팔레트를 seaborn이나 matplotlib에서 바로 쓸 수 있는 컬러맵 객체로도 받아오기도 가능하다. 이는 as_cmap=True 라는 명령어를 쓰면 된다.
x, y = np.random.multivariate_normal([0, 0], [[1, -.5], [-.5, 1]], size=300).T cmap = sns.cubehelix_palette(light=1, as_cmap=True) sns.kdeplot(x, y, cmap=cmap, shade=True);
Python
To help select good palettes or colormaps using this system, you can use the choose_cubehelix_palette() function in a notebook to launch an interactive app that will let you play with the different parameters. Pass as_cmap=True if you want the function to return a colormap (rather than a list) for use in function like hexbin
이런 기능들을 써가며 쓰임새에 알맞은 팔레트나 컬러맵들을 선택하는데에는 choose_cubehelix_palette() 클래스가 도움이 될 것이다. 이는 노트북(주피터 노트북과 같은 노트북 프로그램을 지칭)에서 각기 다른 매개변수들을 가지고 인터렉티브한 어플리케이션을 구현해야할 때 도움이 된다. hexbin 과 같은 그래프 (역주 : 소위 헥사고날바이닝이라 불리는, 육각형 구간 그래프를 지칭) 를 다루고자 할 때 as_camp=True 명령어를 치면 알맞은 컬러맵을 반환해 줄 것이다.

Custom sequential palettes

시퀀셜 팔레트 커스터마이징 하기
For a simpler interface to custom sequential palettes, you can use light_palette() or dark_palette(), which are both seeded with a single color and produce a palette that ramps either from light or dark desaturated values to that color. These functions are also accompanied by the choose_light_palette() and choose_dark_palette() functions that launch interactive widgets to create these palettes.
시퀀셜 팔레트를 커스터마이징 하는 보다 쉬운 인터페이스가 있는데, light_palette()dark_palette()를 쓰는 것이다. 이 두 클래스 모두 하나의 색을 기준으로 점차 밝아지거나 어두워지면서 채도를 변화시킨다. 이 두 기능은 choose_light_palette()choose_dark_palette() 라는 클래스와 연관성이 있으며, 그 클래스들은 팔레트를 만들기 위한 인터렉티브 위젯을 가동시킨다는 공통된 특징이 있다.
sns.palplot(sns.light_palette("green"))
Python
sns.palplot(sns.dark_palette("purple"))
Python
sns.palplot(sns.light_palette("navy", reverse=True))
Python
They can also be used to create colormap objects rather than lists of colors.
이 기능들은 컬러값들이 담긴 리스트가 아니라 컬러맵 객체들을 만든다.
pal = sns.dark_palette("palegreen", as_cmap=True) sns.kdeplot(x, y, cmap=pal);
Python
By default, the input can be any valid matplotlib color. Alternate interpretations are controlled by the input argument. Currently you can provide tuples in hls or husl space along with the default rgb, and you can also seed the palette with any valid xkcd color.
기본적으로는 matplotlib에서 상용되는 모든 색이 다 활용 가능하다. 다른 요소들은 (Alternate interpretations) 명령어 속 인자값들을 조절해주면 된다. 현재까진 hls, husl, xkcd 지정을 기본 rgb값을 담은 튜플과 함께 사용하고 있다.
# 주석: 아래 코드를 보면 기본 rgb 값을 튜플에 넣고, input 에다가 husl을 지정했다. sns.palplot(sns.light_palette((210, 90, 60), input="husl"))
Python
sns.palplot(sns.dark_palette("muted purple", input="xkcd"))
Python
Note that the default input space for the interactive palette widgets is husl, which is different from the default for the function itself, but much more useful in this context.
인터렉티브 위젯의 기본 인풋은 husl이라는 걸 알아두자. 이는 클래스 그 자체가 가진 기본 옵션이랑 다르다. 그러나 husl을 기본으로 쓰는 게 이런 맥락에서는 훨씬 더 유용하다.

Diverging color palettes¶

다이버징(갈라지는) 컬러 팔레트
( 역주 : 다이버징 팔레트는 예시를 먼저 보고 이해하는 게 빠르다)
The third class of color palettes is called “diverging”. These are used for data where both large low and high values are interesting. There is also usually a well-defined midpoint in the data. For instance, if you are plotting changes in temperature from some baseline timepoint, it is best to use a diverging colormap to show areas with relative decreases and areas with relative increases.
세 번째 컬러 팔레트 클래스의 이름은 "다이버징 팔레트"이다. 이는 데이터의 범위가 넓으며 그 저점과 고점이 각각 활용 가치가 있을 때 사용된다. 이런 데이터들은 대개 저점과 고점 사이 중간 지점이 뚜렷하게 나타난다. 예를 들어 특정 시점의 기온의 변화를 그래프로 표기하고 싶다면 그 온도가 상대적으로 감소하는 구간과 증가하는 구간을 각각 디버징 팔레트로 표현하는 게 최적의 방법이라 할 수 있다.
The rules for choosing good diverging palettes are similar to good sequential palettes, except now you want to have two relatively subtle hue shifts from distinct starting hues that meet in an under-emphasized color at the midpoint. It’s also important that the starting values are of similar brightness and saturation.
좋은 다이버징 팔레트를 고르는 방법은 좋은 시퀀셜 팔레트를 고르는 것과 비슷하다. 단지 색이 점차 변해가는 hue를 통한 의미 구분이 두 개이며 그 색이 양 끝으로부터 중간지점에서 만난다는 것이 다를 뿐이다. 중간지점에서부터 양 끝으로 뻗어가기 시작하는 색의 밝기와 채도는 둘 다 비슷하다는 점도 중요한 포인트이다.
It’s also important to emphasize here that using red and green should be avoided, as a substantial population of potential viewers will be unable to distinguish them.
이때 붉은 색과 녹색을 양 끝에 배치해 구분하는 건 피하는 것이 중요하다. 왜냐하면 꽤 많은 사람들이 적녹 색맹 때문에 그 둘을 구분하지 못하기 때문이다.
It should not surprise you that the Color Brewer library comes with a set of well-chosen diverging colormaps.
Color Brewer 라이브러리가 괜찮은 수준의 디버징 컬러맵 세트들을 이미 갖추고 있다는 건 이제 더 이상 놀랄만한 것도 아니다.
sns.palplot(sns.color_palette("BrBG", 7))
Python
sns.palplot(sns.color_palette("RdBu_r", 7))
Python
Another good choice that is built into matplotlib is the coolwarm palette. Note that this colormap has less contrast between the middle values and the extremes.
좋은 팔레트를 고르는 또 다른 방법은 matplotlib의 내장된 팔레트인 coolwarm 팔레트를 쓰는 것이다. 이 컬러맵은 중간지점의 색과 양 끝 색 간의 색상 대비가 크지 않다는 점을 알아두자.
sns.palplot(sns.color_palette("coolwarm", 7))
Python

Custom diverging palettes¶

다이버징 팔레트 커스터마이징하기
You can also use the seaborn function diverging_palette() to create a custom colormap for diverging data. (Naturally there is also a companion interactive widget, choose_diverging_palette()). This function makes diverging palettes using the husl color system. You pass it two hues (in degrees) and, optionally, the lightness and saturation values for the extremes. Using husl means that the extreme values, and the resulting ramps to the midpoint, will be well-balanced.
Seaborn의 diverging_palette() 클래스를 사용해서 양 끝 값들이 나뉘는 데이터에 대해 커스터마이징한 컬러맵을 만들 수 있다. (choose_diverging_palette() 기능을 통해 인터렉티브 위젯도 딸려온다) 이 클래스로 다이버징 팔레트에 husl 컬러 시스템을 도입할 수 있다. 양 끝에 넣을 두 색을 지정해 입력해주고, 추가적인 옵션으로 밝기나 채도를 지정해 주면 된다. husl을 쓴다는 건 양 끝과 중간 지점의 색 모두 밸런스가 잘 맞게 된다는 뜻이다.
sns.palplot(sns.diverging_palette(220, 20, n=7))
Python
sns.palplot(sns.diverging_palette(145, 280, s=85, l=25, n=7))
Python
The sep argument controls the width of the separation between the two ramps in the middle region of the palette.
sep (separation)인자를 추가 삽입하면 양 끝 색으로부터 중간에 위치한, 즉 나뉘는 지점의 폭을 조절해 줄 수 있다.
sns.palplot(sns.diverging_palette(10, 220, sep=80, n=7))
Python
It’s also possible to make a palette with the midpoint is dark rather than light.
중간 지점을 밝게 만드는 게 아닌 어둡게 해서 구분하는 것도 가능하다.
sns.palplot(sns.diverging_palette(255, 133, l=60, n=7, center="dark"))
Python

Setting the default color palette

컬러 팔레트의 기본값 세팅하기
The color_palette() function has a companion called set_palette(). The relationship between them is similar to the pairs covered in the aesthetics tutorial. set_palette() accepts the same arguments as color_palette(), but it changes the default matplotlib parameters so that the palette is used for all plots.
color_palette() 클래스는 set_palett()라는 보조 클래스를 함께 갖고 있다. 둘 사이의 관계는 앞선 튜토리얼에서 파악한 것과 같다. set_palette()color_palette()에서 사용되는 것과 똑같은 인자들이 적용되지만, 그 클래스를 사용하면 matplotlib의 기본 설정들이 바뀌면서 그 팔레트가 모든 그래프에 적용된다.
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
sns.set_palette("husl") sinplot()
Python
The color_palette() function can also be used in a with statement to temporarily change the color palette.
앞선 튜토리얼에서도 확인했듯 color_palette()with 구문을 사용해서 임시적으로 컬러 팔레트를 바꾸는 것이 가능하다.
with sns.color_palette("PuBuGn_d"): sinplot()
Python