[Python] matplotlib colormap, colorbar 사용 방법

2024. 12. 7. 01:40·프로그래밍 Programming/파이썬 Python

 

 

Matplotlib의 버전에 따라서 colormap과 colorbar 사용법이 조금씩 다른데 여기서는 3.9를 기준으로 설명한다.

 

 

 

colormap을 불러들이는 함수는 어떤 코드를 보느냐에 따라서 약간씩 달라질 수 있다.

그러나 기본적으로는 colormap을 가져오고 [0,1] 사이의 값을 지정해서 color에 해당하는 RGBA 값(사이즈 4 벡터)을 가져올 수 있다는 점에서 같다.

 

 

1) Colormap

 

colormap 지정은 코드를 어떤 걸 쓰느냐에 따라 다르지만 방법은 다양하다.

 

다음과 같이 map을 가져올 경우

cmap = matplotlib.colormaps.get_cmap("viridis")
cmap( np.lispace(0.0, 1.0, 20) ) # extract 20 colors from cmap

 

다음과 같이 [0,1] 사이 값을 넣어서 컬러벡터를 뽑아서 쓸 수 있다.

 

 

 

import matplotlib.pyplot as plt
import numpy as np

import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap, ListedColormap

viridis = mpl.colormaps['viridis'].resampled(8)

 

다음과 같이 colormap을 resample한 경우에는 총 colormap에서 8개의 sample이 나오게 된다.

 

print('viridis.colors', viridis.colors)
print('viridis(range(8))', viridis(range(8)))
print('viridis(np.linspace(0, 1, 8))', viridis(np.linspace(0, 1, 8)))

 

 

더 심화된 방법으로는 colormap을 새로 만드는 방법도 있는데 이는 생략한다. 자세한 내용은

https://matplotlib.org/stable/users/explain/colors/colormap-manipulation.html#colormap-manipulation

 

Creating Colormaps in Matplotlib — Matplotlib 3.9.3 documentation

Creating Colormaps in Matplotlib Matplotlib has a number of built-in colormaps accessible via matplotlib.colormaps. There are also external libraries like palettable that have many extra colormaps. However, we may also want to create or manipulate our own

matplotlib.org

다음 링크를 참고해서 보면 된다.

 

 

 

 

2) Colorbar

 


stack overflow에 있는 colormap과 colorbar를 사용하는 예제는 다음과 같다.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors


def func(x, a):
    return np.exp(-x * a)

x = np.linspace(0, 5)

fig, ax = plt.subplots()

# define color map
# cmap = cm.get_cmap("Spectral") # this is obsolete after mapplotlib 3.7
cmap = matplotlib.colormaps.get_cmap("Spectral")

# need to normalize because color maps are defined in [0, 1]
norm = colors.Normalize(0, 5)

for a in range(1, 5):
    ax.plot(x, func(x, a), 
        color=cmap(norm(a)))  # get color from color map 

# plot colorbar
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)

plt.show()

 

다음과 같이 cmap 자체를 저장해놓고 colors.Normalize 를 적용해서 다른 scalar 값을 [0,1] 사이로 mapping하는 방법을 쓸 수 있다.

 

 

colorbar의 경우에는 cm.ScalarMappable을 반드시 입력으로 받게 되어있다. 즉, cm.ScalarMappable를 알아야하는데 cm.ScalarMappable(norm=norm, cmap=cmap)의 경우에는 scalar data를 RGBA로 mapping해주는 class이다.

 

 

 

 

 

따라서 아래와 같이 norm에 cm.Normalize 를 넣어서 사용하면 된다.

fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)

 

 

 

 


 

 

https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.colorbar.html#matplotlib.figure.Figure.colorbar

https://matplotlib.org/stable/api/_as_gen/matplotlib.colors.Colormap.html#matplotlib.colors.Colormap

https://matplotlib.org/stable/api/cm_api.html#matplotlib.cm.ScalarMappable

https://matplotlib.org/stable/api/_as_gen/matplotlib.colors.Normalize.html#matplotlib.colors.Normalize

저작자표시 비영리 변경금지 (새창열림)

'프로그래밍 Programming > 파이썬 Python' 카테고리의 다른 글

[에러기록] moviewriter ffmpeg unavailable; using pillow instead.  (0) 2024.04.17
[python] Visual studio code에서 다운받은 패키지 사용하기(경로 설정 등)  (0) 2024.04.16
[matplotlib] matplotlib에서 latex 사용 오류  (0) 2024.01.26
[matplotlib] 그래프 색상/마커 다르게 그리기  (0) 2023.09.18
[Python] MCMC Sampling library  (0) 2023.08.24
'프로그래밍 Programming/파이썬 Python' 카테고리의 다른 글
  • [에러기록] moviewriter ffmpeg unavailable; using pillow instead.
  • [python] Visual studio code에서 다운받은 패키지 사용하기(경로 설정 등)
  • [matplotlib] matplotlib에서 latex 사용 오류
  • [matplotlib] 그래프 색상/마커 다르게 그리기
보통의공대생
보통의공대생
수학,프로그래밍,기계항공우주 등 공부하는 기록들을 남깁니다.
  • 보통의공대생
    뛰는 놈 위에 나는 공대생
    보통의공대생
  • 전체
    오늘
    어제
    • 분류 전체보기 (459) N
      • 공지 (1)
      • 영어 공부 English Study (40)
        • 텝스 TEPS (7)
        • 글 Article (21)
        • 영상 Video (10)
      • 연구 Research (99)
        • 최적화 Optimization (3)
        • 데이터과학 Data Science (7)
        • 인공지능 Artificial Intelligent (40)
        • 제어 Control (45)
      • 프로그래밍 Programming (103)
        • 매트랩 MATLAB (25)
        • 파이썬 Python (33)
        • 줄리아 Julia (2)
        • C++ (3)
        • 리눅스 우분투 Ubuntu (6)
      • 항공우주 Aeronautical engineeri.. (21)
        • 항법 Navigation (0)
        • 유도 Guidance (0)
      • 기계공학 Mechanical engineering (13)
        • 열역학 Thermodynamics (0)
        • 고체역학 Statics & Solid mechan.. (10)
        • 동역학 Dynamics (1)
        • 유체역학 Fluid Dynamics (0)
      • 수학 Mathematics (34)
        • 선형대수학 Linear Algebra (18)
        • 미분방정식 Differential Equation (3)
        • 확률및통계 Probability & Sta.. (2)
        • 미적분학 Calculus (1)
        • 복소해석학 Complex Analysis (5)
        • 실해석학 Real Analysis (0)
      • 수치해석 Numerical Analysis (21)
      • 확률 및 랜덤프로세스 Random process (2)
      • 추론 & 추정 이론 Estimation (3)
      • 기타 (26)
        • 설계 프로젝트 System Design (8)
        • 논문작성 Writing (55)
        • 세미나 Seminar (2)
        • 생산성 Productivity (3)
      • 유학 생활 Daily (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Statics
    MATLAB
    우분투
    Zotero
    옵시디언
    Numerical Analysis
    WOX
    논문작성법
    텝스
    pytorch
    Dear abby
    고체역학
    생산성
    teps
    Python
    JAX
    딥러닝
    obsidian
    서버
    논문작성
    Julia
    ChatGPT
    Linear algebra
    텝스공부
    matplotlib
    IEEE
    인공지능
    수치해석
    LaTeX
    에러기록
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
보통의공대생
[Python] matplotlib colormap, colorbar 사용 방법
상단으로

티스토리툴바