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
다음 링크를 참고해서 보면 된다.
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.colors.Colormap.html#matplotlib.colors.Colormap
https://matplotlib.org/stable/api/cm_api.html#matplotlib.cm.ScalarMappable
'프로그래밍 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 |