🚴‍♂️
TIL
  • MAIN
  • : TIL?
  • : WIL
  • : Plan
  • : Retrospective
    • 21Y
      • Wait a moment!
      • 9M 2W
      • 9M1W
      • 8M4W
      • 8M3W
      • 8M2W
      • 8M1W
      • 7M4W
      • 7M3W
      • 7M2W
      • 7M1W
      • 6M5W
      • 1H
    • 새사람 되기 프로젝트
      • 2회차
      • 1회차
  • TIL : ML
    • Paper Analysis
      • BERT
      • Transformer
    • Boostcamp 2st
      • [S]Data Viz
        • (4-3) Seaborn 심화
        • (4-2) Seaborn 기초
        • (4-1) Seaborn 소개
        • (3-4) More Tips
        • (3-3) Facet 사용하기
        • (3-2) Color 사용하기
        • (3-1) Text 사용하기
        • (2-3) Scatter Plot 사용하기
        • (2-2) Line Plot 사용하기
        • (2-1) Bar Plot 사용하기
        • (1-3) Python과 Matplotlib
        • (1-2) 시각화의 요소
        • (1-1) Welcome to Visualization (OT)
      • [P]MRC
        • (2강) Extraction-based MRC
        • (1강) MRC Intro & Python Basics
      • [P]KLUE
        • (5강) BERT 기반 단일 문장 분류 모델 학습
        • (4강) 한국어 BERT 언어 모델 학습
        • [NLP] 문장 내 개체간 관계 추출
        • (3강) BERT 언어모델 소개
        • (2강) 자연어의 전처리
        • (1강) 인공지능과 자연어 처리
      • [U]Stage-CV
      • [U]Stage-NLP
        • 7W Retrospective
        • (10강) Advanced Self-supervised Pre-training Models
        • (09강) Self-supervised Pre-training Models
        • (08강) Transformer (2)
        • (07강) Transformer (1)
        • 6W Retrospective
        • (06강) Beam Search and BLEU score
        • (05강) Sequence to Sequence with Attention
        • (04강) LSTM and GRU
        • (03강) Recurrent Neural Network and Language Modeling
        • (02강) Word Embedding
        • (01강) Intro to NLP, Bag-of-Words
        • [필수 과제 4] Preprocessing for NMT Model
        • [필수 과제 3] Subword-level Language Model
        • [필수 과제2] RNN-based Language Model
        • [선택 과제] BERT Fine-tuning with transformers
        • [필수 과제] Data Preprocessing
      • Mask Wear Image Classification
        • 5W Retrospective
        • Report_Level1_6
        • Performance | Review
        • DAY 11 : HardVoting | MultiLabelClassification
        • DAY 10 : Cutmix
        • DAY 9 : Loss Function
        • DAY 8 : Baseline
        • DAY 7 : Class Imbalance | Stratification
        • DAY 6 : Error Fix
        • DAY 5 : Facenet | Save
        • DAY 4 : VIT | F1_Loss | LrScheduler
        • DAY 3 : DataSet/Lodaer | EfficientNet
        • DAY 2 : Labeling
        • DAY 1 : EDA
        • 2_EDA Analysis
      • [P]Stage-1
        • 4W Retrospective
        • (10강) Experiment Toolkits & Tips
        • (9강) Ensemble
        • (8강) Training & Inference 2
        • (7강) Training & Inference 1
        • (6강) Model 2
        • (5강) Model 1
        • (4강) Data Generation
        • (3강) Dataset
        • (2강) Image Classification & EDA
        • (1강) Competition with AI Stages!
      • [U]Stage-3
        • 3W Retrospective
        • PyTorch
          • (10강) PyTorch Troubleshooting
          • (09강) Hyperparameter Tuning
          • (08강) Multi-GPU 학습
          • (07강) Monitoring tools for PyTorch
          • (06강) 모델 불러오기
          • (05강) Dataset & Dataloader
          • (04강) AutoGrad & Optimizer
          • (03강) PyTorch 프로젝트 구조 이해하기
          • (02강) PyTorch Basics
          • (01강) Introduction to PyTorch
      • [U]Stage-2
        • 2W Retrospective
        • DL Basic
          • (10강) Generative Models 2
          • (09강) Generative Models 1
          • (08강) Sequential Models - Transformer
          • (07강) Sequential Models - RNN
          • (06강) Computer Vision Applications
          • (05강) Modern CNN - 1x1 convolution의 중요성
          • (04강) Convolution은 무엇인가?
          • (03강) Optimization
          • (02강) 뉴럴 네트워크 - MLP (Multi-Layer Perceptron)
          • (01강) 딥러닝 기본 용어 설명 - Historical Review
        • Assignment
          • [필수 과제] Multi-headed Attention Assignment
          • [필수 과제] LSTM Assignment
          • [필수 과제] CNN Assignment
          • [필수 과제] Optimization Assignment
          • [필수 과제] MLP Assignment
      • [U]Stage-1
        • 1W Retrospective
        • AI Math
          • (AI Math 10강) RNN 첫걸음
          • (AI Math 9강) CNN 첫걸음
          • (AI Math 8강) 베이즈 통계학 맛보기
          • (AI Math 7강) 통계학 맛보기
          • (AI Math 6강) 확률론 맛보기
          • (AI Math 5강) 딥러닝 학습방법 이해하기
          • (AI Math 4강) 경사하강법 - 매운맛
          • (AI Math 3강) 경사하강법 - 순한맛
          • (AI Math 2강) 행렬이 뭐예요?
          • (AI Math 1강) 벡터가 뭐예요?
        • Python
          • (Python 7-2강) pandas II
          • (Python 7-1강) pandas I
          • (Python 6강) numpy
          • (Python 5-2강) Python data handling
          • (Python 5-1강) File / Exception / Log Handling
          • (Python 4-2강) Module and Project
          • (Python 4-1강) Python Object Oriented Programming
          • (Python 3-2강) Pythonic code
          • (Python 3-1강) Python Data Structure
          • (Python 2-4강) String and advanced function concept
          • (Python 2-3강) Conditionals and Loops
          • (Python 2-2강) Function and Console I/O
          • (Python 2-1강) Variables
          • (Python 1-3강) 파이썬 코딩 환경
          • (Python 1-2강) 파이썬 개요
          • (Python 1-1강) Basic computer class for newbies
        • Assignment
          • [선택 과제 3] Maximum Likelihood Estimate
          • [선택 과제 2] Backpropagation
          • [선택 과제 1] Gradient Descent
          • [필수 과제 5] Morsecode
          • [필수 과제 4] Baseball
          • [필수 과제 3] Text Processing 2
          • [필수 과제 2] Text Processing 1
          • [필수 과제 1] Basic Math
    • 딥러닝 CNN 완벽 가이드 - Fundamental 편
      • 종합 실습 2 - 캐글 Plant Pathology(나무잎 병 진단) 경연 대회
      • 종합 실습 1 - 120종의 Dog Breed Identification 모델 최적화
      • 사전 훈련 모델의 미세 조정 학습과 다양한 Learning Rate Scheduler의 적용
      • Advanced CNN 모델 파헤치기 - ResNet 상세와 EfficientNet 개요
      • Advanced CNN 모델 파헤치기 - AlexNet, VGGNet, GoogLeNet
      • Albumentation을 이용한 Augmentation기법과 Keras Sequence 활용하기
      • 사전 훈련 CNN 모델의 활용과 Keras Generator 메커니즘 이해
      • 데이터 증강의 이해 - Keras ImageDataGenerator 활용
      • CNN 모델 구현 및 성능 향상 기본 기법 적용하기
    • AI School 1st
    • 현업 실무자에게 배우는 Kaggle 머신러닝 입문
    • 파이썬 딥러닝 파이토치
  • TIL : Python & Math
    • Do It! 장고+부트스트랩: 파이썬 웹개발의 정석
      • Relations - 다대다 관계
      • Relations - 다대일 관계
      • 템플릿 파일 모듈화 하기
      • TDD (Test Driven Development)
      • template tags & 조건문
      • 정적 파일(static files) & 미디어 파일(media files)
      • FBV (Function Based View)와 CBV (Class Based View)
      • Django 입문하기
      • 부트스트랩
      • 프론트엔드 기초다지기 (HTML, CSS, JS)
      • 들어가기 + 환경설정
    • Algorithm
      • Programmers
        • Level1
          • 소수 만들기
          • 숫자 문자열과 영단어
          • 자연수 뒤집어 배열로 만들기
          • 정수 내림차순으로 배치하기
          • 정수 제곱근 판별
          • 제일 작은 수 제거하기
          • 직사각형 별찍기
          • 짝수와 홀수
          • 체육복
          • 최대공약수와 최소공배수
          • 콜라츠 추측
          • 크레인 인형뽑기 게임
          • 키패드 누르기
          • 평균 구하기
          • 폰켓몬
          • 하샤드 수
          • 핸드폰 번호 가리기
          • 행렬의 덧셈
        • Level2
          • 숫자의 표현
          • 순위 검색
          • 수식 최대화
          • 소수 찾기
          • 소수 만들기
          • 삼각 달팽이
          • 문자열 압축
          • 메뉴 리뉴얼
          • 더 맵게
          • 땅따먹기
          • 멀쩡한 사각형
          • 괄호 회전하기
          • 괄호 변환
          • 구명보트
          • 기능 개발
          • 뉴스 클러스터링
          • 다리를 지나는 트럭
          • 다음 큰 숫자
          • 게임 맵 최단거리
          • 거리두기 확인하기
          • 가장 큰 정사각형 찾기
          • H-Index
          • JadenCase 문자열 만들기
          • N개의 최소공배수
          • N진수 게임
          • 가장 큰 수
          • 124 나라의 숫자
          • 2개 이하로 다른 비트
          • [3차] 파일명 정렬
          • [3차] 압축
          • 줄 서는 방법
          • [3차] 방금 그곡
          • 거리두기 확인하기
        • Level3
          • 매칭 점수
          • 외벽 점검
          • 기지국 설치
          • 숫자 게임
          • 110 옮기기
          • 광고 제거
          • 길 찾기 게임
          • 셔틀버스
          • 단속카메라
          • 표 편집
          • N-Queen
          • 징검다리 건너기
          • 최고의 집합
          • 합승 택시 요금
          • 거스름돈
          • 하노이의 탑
          • 멀리 뛰기
          • 모두 0으로 만들기
        • Level4
    • Head First Python
    • 데이터 분석을 위한 SQL
    • 단 두 장의 문서로 데이터 분석과 시각화 뽀개기
    • Linear Algebra(Khan Academy)
    • 인공지능을 위한 선형대수
    • Statistics110
  • TIL : etc
    • [따배런] Kubernetes
    • [따배런] Docker
      • 2. 도커 설치 실습 1 - 학습편(준비물/실습 유형 소개)
      • 1. 컨테이너와 도커의 이해 - 컨테이너를 쓰는이유 / 일반프로그램과 컨테이너프로그램의 차이점
      • 0. 드디어 찾아온 Docker 강의! 왕초보에서 도커 마스터로 - OT
    • CoinTrading
      • [가상 화폐 자동 매매 프로그램] 백테스팅 : 간단한 테스팅
    • Gatsby
      • 01 깃북 포기 선언
  • TIL : Project
    • Mask Wear Image Classification
    • Project. GARIGO
  • 2021 TIL
    • CHANGED
    • JUN
      • 30 Wed
      • 29 Tue
      • 28 Mon
      • 27 Sun
      • 26 Sat
      • 25 Fri
      • 24 Thu
      • 23 Wed
      • 22 Tue
      • 21 Mon
      • 20 Sun
      • 19 Sat
      • 18 Fri
      • 17 Thu
      • 16 Wed
      • 15 Tue
      • 14 Mon
      • 13 Sun
      • 12 Sat
      • 11 Fri
      • 10 Thu
      • 9 Wed
      • 8 Tue
      • 7 Mon
      • 6 Sun
      • 5 Sat
      • 4 Fri
      • 3 Thu
      • 2 Wed
      • 1 Tue
    • MAY
      • 31 Mon
      • 30 Sun
      • 29 Sat
      • 28 Fri
      • 27 Thu
      • 26 Wed
      • 25 Tue
      • 24 Mon
      • 23 Sun
      • 22 Sat
      • 21 Fri
      • 20 Thu
      • 19 Wed
      • 18 Tue
      • 17 Mon
      • 16 Sun
      • 15 Sat
      • 14 Fri
      • 13 Thu
      • 12 Wed
      • 11 Tue
      • 10 Mon
      • 9 Sun
      • 8 Sat
      • 7 Fri
      • 6 Thu
      • 5 Wed
      • 4 Tue
      • 3 Mon
      • 2 Sun
      • 1 Sat
    • APR
      • 30 Fri
      • 29 Thu
      • 28 Wed
      • 27 Tue
      • 26 Mon
      • 25 Sun
      • 24 Sat
      • 23 Fri
      • 22 Thu
      • 21 Wed
      • 20 Tue
      • 19 Mon
      • 18 Sun
      • 17 Sat
      • 16 Fri
      • 15 Thu
      • 14 Wed
      • 13 Tue
      • 12 Mon
      • 11 Sun
      • 10 Sat
      • 9 Fri
      • 8 Thu
      • 7 Wed
      • 6 Tue
      • 5 Mon
      • 4 Sun
      • 3 Sat
      • 2 Fri
      • 1 Thu
    • MAR
      • 31 Wed
      • 30 Tue
      • 29 Mon
      • 28 Sun
      • 27 Sat
      • 26 Fri
      • 25 Thu
      • 24 Wed
      • 23 Tue
      • 22 Mon
      • 21 Sun
      • 20 Sat
      • 19 Fri
      • 18 Thu
      • 17 Wed
      • 16 Tue
      • 15 Mon
      • 14 Sun
      • 13 Sat
      • 12 Fri
      • 11 Thu
      • 10 Wed
      • 9 Tue
      • 8 Mon
      • 7 Sun
      • 6 Sat
      • 5 Fri
      • 4 Thu
      • 3 Wed
      • 2 Tue
      • 1 Mon
    • FEB
      • 28 Sun
      • 27 Sat
      • 26 Fri
      • 25 Thu
      • 24 Wed
      • 23 Tue
      • 22 Mon
      • 21 Sun
      • 20 Sat
      • 19 Fri
      • 18 Thu
      • 17 Wed
      • 16 Tue
      • 15 Mon
      • 14 Sun
      • 13 Sat
      • 12 Fri
      • 11 Thu
      • 10 Wed
      • 9 Tue
      • 8 Mon
      • 7 Sun
      • 6 Sat
      • 5 Fri
      • 4 Thu
      • 3 Wed
      • 2 Tue
      • 1 Mon
    • JAN
      • 31 Sun
      • 30 Sat
      • 29 Fri
      • 28 Thu
      • 27 Wed
      • 26 Tue
      • 25 Mon
      • 24 Sun
      • 23 Sat
      • 22 Fri
      • 21 Thu
      • 20 Wed
      • 19 Tue
      • 18 Mon
      • 17 Sun
      • 16 Sat
      • 15 Fri
      • 14 Thu
      • 13 Wed
      • 12 Tue
      • 11 Mon
      • 10 Sun
      • 9 Sat
      • 8 Fri
      • 7 Thu
      • 6 Wed
      • 5 Tue
      • 4 Mon
      • 3 Sun
      • 2 Sat
      • 1 Fri
  • 2020 TIL
    • DEC
      • 31 Thu
      • 30 Wed
      • 29 Tue
      • 28 Mon
      • 27 Sun
      • 26 Sat
      • 25 Fri
      • 24 Thu
      • 23 Wed
      • 22 Tue
      • 21 Mon
      • 20 Sun
      • 19 Sat
      • 18 Fri
      • 17 Thu
      • 16 Wed
      • 15 Tue
      • 14 Mon
      • 13 Sun
      • 12 Sat
      • 11 Fri
      • 10 Thu
      • 9 Wed
      • 8 Tue
      • 7 Mon
      • 6 Sun
      • 5 Sat
      • 4 Fri
      • 3 Tue
      • 2 Wed
      • 1 Tue
    • NOV
      • 30 Mon
Powered by GitBook
On this page
  • 1. Color에 대한 이해
  • 1.1 색이 중요한 이유
  • 1.2 화려함이 시각화의 전부는 아니다.
  • 1.3 색이 가지는 의미
  • 2. Color Palette의 종류
  • 2.1 범주형
  • 2.2 연속형
  • 2.3 발산형
  • 3. 그 외 색 Tips
  • 3.1 강조와 색상 대비
  • 3.2 색각 이상
  • 3-2. Color
  • 0. 색상 더 이해하기
  • 1. 범주형 색상 (Qualitative)
  • 2. 연속형 색상
  • 3. 발산형 색상
  • 4. 색상 대비 더 이해하기

Was this helpful?

  1. TIL : ML
  2. Boostcamp 2st
  3. [S]Data Viz

(3-2) Color 사용하기

210820

Previous(3-3) Facet 사용하기Next(3-1) Text 사용하기

Last updated 3 years ago

Was this helpful?

1. Color에 대한 이해

1.1 색이 중요한 이유

색이 주는 느낌이 있기 때문이다. 파란색을 시원함, 빨간색은 뜨거움. 물론 모든 사람이 공통적으로 느끼지는 않는다.

1.2 화려함이 시각화의 전부는 아니다.

왼쪽 그래프는 화려하고 예쁘지만 독자에게 주고자 하는 인사이트가 무엇인지 알기 힘들다.

1.3 색이 가지는 의미

높은 온도에는 빨간색, 낮은 온도에는 파란색을 주로 사용한다. 카카오는 노란색, 네이버는 초록색을 사용한다. 이렇게 기존 정보와 느낌을 잘 활용하는 것이 중요하다.

어떤 색을 사용할지 결정하기가 어렵다면 조사를 통해 결정하라. 이미 사용하는 색에는 이유가 있다.

2. Color Palette의 종류

2.1 범주형

최대 10개까지 색을 사용하되, 너무 많이 사용하는 것은 지양하도록 한다. 이러한 색들은 색의 차이로 구분하는 것이 특징이며 채도나 명도를 개별적으로 조정하는 것도 지양해야 한다.

2.2 연속형

연속적인 색상을 사용하여 값을 표현한다. 어두운 배경에서는 밝은 색, 밝은 배경에서는 어두운 색이 큰 값을 표현한다. 색상은 단일 색조로 표현하는 것이 좋고 균일한 색상 변화가 중요하다.

2.3 발산형

연속형과 유사하지만 중앙을 기준으로 발산한다. 상반된 값을 나타낼 때 효과적이며 양 끝으로 갈 수록 색이 진해지는 특징이 있다.

3. 그 외 색 Tips

3.1 강조와 색상 대비

데이터에서 다름을 보이기 위해 하이라이팅을 할 수 있다. 강조를 위한 방법 중 하나가 색상 대비이다.

  • 명도 대비 : 밝은 색과 어두운 색을 배치하면 밝은 색은 더 밝게, 어두운 색은 더 어둡게 보인다

  • 색상 대비 : 가까운 색의 차이가 더 크게 보인다

  • 채도 대비 : 채도의 차이. 채도가 더 높아보인다

  • 보색 대비 : 정반대 색상을 사용하면 더 선명해 보인다

3.2 색각 이상

  • 삼원색 중에 특정 색을 감지 못하면 색맹

  • 부분적 인지 이상이 있다면 색약

3-2. Color

0. 색상 더 이해하기

색을 이해하기 위해서는 rgb보다 hsl을 이해하는 것이 중요합니다.

  • Hue(색조) : 빨강, 파랑, 초록 등 색상으로 생각하는 부분

    • 빨강에서 보라색까지 있는 스펙트럼에서 0-360으로 표현

  • Saturate(채도) : 무채색과의 차이

    • 선명도라고 볼 수 있음 (선명하다와 탁하다.)

  • Lightness(광도) : 색상의 밝기

등 다양한 색상을 살펴보며 아래의 분류들을 잘 활용하면 좋습니다.

그리고 추후에는 다음과 같은 도구로 색상을 선택할 수도 있습니다.

1. 범주형 색상 (Qualitative)

이미 앞서서 많이 사용했던 범주별 분류입니다.

Built-in Colormap을 사용하여 다양한 표현방법을 살펴보도록 하겠습니,

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
student = pd.read_csv('./StudentsPerformance.csv')
student.head()

gender

race/ethnicity

parental level of education

lunch

test preparation course

math score

reading score

writing score

0

female

group B

bachelor's degree

standard

none

72

72

74

1

female

group C

some college

standard

completed

69

90

88

2

female

group B

master's degree

standard

none

90

95

93

3

male

group A

associate's degree

free/reduced

none

47

57

44

4

male

group C

some college

standard

none

76

78

75

1-1. 색 살펴보기

matplotlib의 colormap을 다루는 것은 살짝 복잡합니다. 강의에서는 일부 테크닉을 소개합니다.

# Group to Number
groups = sorted(student['race/ethnicity'].unique())
gton = dict(zip(groups , range(5)))

# Group에 따라 색 1, 2, 3, 4, 5
student['color'] = student['race/ethnicity'].map(gton)
# color list to color map
print(plt.cm.get_cmap('tab10').colors)
((0.12156862745098039, 0.4666666666666667, 0.7058823529411765), (1.0, 0.4980392156862745, 0.054901960784313725), (0.17254901960784313, 0.6274509803921569, 0.17254901960784313), (0.8392156862745098, 0.15294117647058825, 0.1568627450980392), (0.5803921568627451, 0.403921568627451, 0.7411764705882353), (0.5490196078431373, 0.33725490196078434, 0.29411764705882354), (0.8901960784313725, 0.4666666666666667, 0.7607843137254902), (0.4980392156862745, 0.4980392156862745, 0.4980392156862745), (0.7372549019607844, 0.7411764705882353, 0.13333333333333333), (0.09019607843137255, 0.7450980392156863, 0.8117647058823529))

범주형 색상은 채도와 광도는 거의 일정하고, 색상의 변화만으로 차이를 주는 것이 특징입니다.

from matplotlib.colors import ListedColormap

qualitative_cm_list = ['Pastel1', 'Pastel2', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10']

fig, axes = plt.subplots(2, 4, figsize=(20, 8))
axes = axes.flatten()

student_sub = student.sample(100)

for idx, cm in enumerate(qualitative_cm_list):    
    pcm = axes[idx].scatter(student_sub['math score'], student_sub['reading score'],
                     c=student_sub['color'], cmap=ListedColormap(plt.cm.get_cmap(cm).colors[:5])
                     )
    cbar = fig.colorbar(pcm, ax=axes[idx], ticks=range(5))
    cbar.ax.set_yticklabels(groups)
    axes[idx].set_title(cm)
    
plt.show()

이산적인 색을 사용한 막대그래프와 라인그래프는 이미 앞서 살펴봤습니다. 추후 이산적인 색상은 seaborn에서 적용하며 살펴보겠습니다.

일반적으로 tab10과 Set2가 가장 많이 사용되고 더 많은 색은 위에서 언급한 R colormap을 사용하면 좋습니다.

2. 연속형 색상

  • 막대 그래프에서는 잘 사용하지 않고 2차원 데이터에서 사용한다

  • Heatmap, Contour Plot

  • 지리지도 데이터, 계층형 데이터에도 적합

2-1. 색 살펴보기

색조는 유지하되 색의 밝기를 조정하여 연속적인 표현을 나타냅니다.

sequential_cm_list = ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
            'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
            'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']

fig, axes = plt.subplots(3, 6, figsize=(25, 10))
axes = axes.flatten()

student_sub = student.sample(100)

for idx, cm in enumerate(sequential_cm_list):    
    pcm = axes[idx].scatter(student['math score'], student['reading score'],
                            c=student['reading score'], 
                            cmap=cm,
                            vmin=0, vmax=100
                    
                     )
    fig.colorbar(pcm, ax=axes[idx])
    axes[idx].set_title(cm)
    
plt.show()

2-2. imshow

이미지 정보를 2d-array로 받아서 색상을 표현한다.

im = np.arange(100).reshape(10, 10)
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(im)
plt.show()

이를 활용하면 깃헙 잔디밭도 만들 수 있습니다.

im =  np.random.randint(10, size=(7, 52))
fig, ax = plt.subplots(figsize=(20, 5))
ax.imshow(im, cmap='Greens')
ax.set_yticks(np.arange(7)+0.5, minor=True)
ax.set_xticks(np.arange(52)+0.5, minor=True)
ax.grid(which='minor', color="w", linestyle='-', linewidth=3)
plt.show()

3. 발산형 색상

  • 어디를 중심으로 삼을 것인가

  • 상관관계 등

  • Geospatial

3-1. 색 살펴보기

from matplotlib.colors import TwoSlopeNorm

diverging_cm_list = ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
            'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']

fig, axes = plt.subplots(3, 4, figsize=(20, 15))
axes = axes.flatten()

offset = TwoSlopeNorm(vmin=0, vcenter=student['reading score'].mean(), vmax=100)

student_sub = student.sample(100)

for idx, cm in enumerate(diverging_cm_list):    
    pcm = axes[idx].scatter(student['math score'], student['reading score'],
                            c=offset(student['math score']), 
                            cmap=cm,
                     )
    cbar = fig.colorbar(pcm, ax=axes[idx], 
                        ticks=[0, 0.5, 1], 
                        orientation='horizontal'
                       )
    cbar.ax.set_xticklabels([0, student['math score'].mean(), 100])
    axes[idx].set_title(cm)
    
plt.show()

4. 색상 대비 더 이해하기

4-0. 특정 부분 강조를 위한 시각화

fig = plt.figure(figsize=(18, 15))
groups = student['race/ethnicity'].value_counts().sort_index()

ax_bar = fig.add_subplot(2, 1, 1)
ax_bar.bar(groups.index, groups, width=0.5)

ax_s1 = fig.add_subplot(2, 3, 4)
ax_s2 = fig.add_subplot(2, 3, 5)
ax_s3 = fig.add_subplot(2, 3, 6)

ax_s1.scatter(student['math score'], student['reading score'])
ax_s2.scatter(student['math score'], student['writing score'])
ax_s3.scatter(student['writing score'], student['reading score'])

for ax in [ax_s1, ax_s2, ax_s3]:
    ax.set_xlim(-2, 105)
    ax.set_ylim(-2, 105)

plt.show()

4-1. 명도 대비

a_color, nota_color = 'black', 'lightgray'

colors = student['race/ethnicity'].apply(lambda x : a_color if x =='group A' else nota_color)
color_bars = [a_color] + [nota_color]*4

fig = plt.figure(figsize=(18, 15))
groups = student['race/ethnicity'].value_counts().sort_index()

ax_bar = fig.add_subplot(2, 1, 1)
ax_bar.bar(groups.index, groups, color=color_bars, width=0.5)

ax_s1 = fig.add_subplot(2, 3, 4)
ax_s2 = fig.add_subplot(2, 3, 5)
ax_s3 = fig.add_subplot(2, 3, 6)

ax_s1.scatter(student['math score'], student['reading score'], color=colors, alpha=0.5)
ax_s2.scatter(student['math score'], student['writing score'], color=colors, alpha=0.5)
ax_s3.scatter(student['writing score'], student['reading score'], color=colors, alpha=0.5)

for ax in [ax_s1, ax_s2, ax_s3]:
    ax.set_xlim(-2, 105)
    ax.set_ylim(-2, 105)

plt.show()

4-2. 채도 대비

a_color, nota_color = 'orange', 'lightgray'

colors = student['race/ethnicity'].apply(lambda x : a_color if x =='group A' else nota_color)
color_bars = [a_color] + [nota_color]*4

fig = plt.figure(figsize=(18, 15))
groups = student['race/ethnicity'].value_counts().sort_index()

ax_bar = fig.add_subplot(2, 1, 1)
ax_bar.bar(groups.index, groups, color=color_bars, width=0.5)

ax_s1 = fig.add_subplot(2, 3, 4)
ax_s2 = fig.add_subplot(2, 3, 5)
ax_s3 = fig.add_subplot(2, 3, 6)

ax_s1.scatter(student['math score'], student['reading score'], color=colors, alpha=0.3)
ax_s2.scatter(student['math score'], student['writing score'], color=colors, alpha=0.3)
ax_s3.scatter(student['writing score'], student['reading score'], color=colors, alpha=0.3)

for ax in [ax_s1, ax_s2, ax_s3]:
    ax.set_xlim(-2, 105)
    ax.set_ylim(-2, 105)

plt.show()

4-3. 보색 대비

a_color, nota_color = 'tomato', 'lightgreen'

colors = student['race/ethnicity'].apply(lambda x : a_color if x =='group A' else nota_color)
color_bars = [a_color] + [nota_color]*4

fig = plt.figure(figsize=(18, 15))
groups = student['race/ethnicity'].value_counts().sort_index()

ax_bar = fig.add_subplot(2, 1, 1)
ax_bar.bar(groups.index, groups, color=color_bars, width=0.5)

ax_s1 = fig.add_subplot(2, 3, 4)
ax_s2 = fig.add_subplot(2, 3, 5)
ax_s3 = fig.add_subplot(2, 3, 6)

ax_s1.scatter(student['math score'], student['reading score'], color=colors, alpha=0.3)
ax_s2.scatter(student['math score'], student['writing score'], color=colors, alpha=0.3)
ax_s3.scatter(student['writing score'], student['reading score'], color=colors, alpha=0.3)

for ax in [ax_s1, ax_s2, ax_s3]:
    ax.set_xlim(-2, 105)
    ax.set_ylim(-2, 105)

plt.show()

matplotlib에서 다양한 를 제공하고 있으니 참고하길 바랍니다.

color api
Github Topic Color-palette
karthik/wesanderson
Top R Color Palettes to Know for Great Data Visualization
Adobe Color