однородный numpy массив отображает один и тот же cmap matplotlib независимо от значения - PullRequest
0 голосов
/ 01 августа 2020

Я пытался отладить некоторый код визуализации, и когда я вернулся к ультра-основам, я обнаружил сбивающее с толку поведение, которое заставляет меня думать, что я что-то принципиально упускаю в cmaps matplotlib.

Это работает как i ожидайте - печать диапазона красных и синих оттенков, соответствующих случайно сгенерированным значениям от 0,1.

fig = plt.figure()
CMAP =  "seismic"   # blue-white-red colormap
a = np.array(np.random.rand(50,50)/2,).reshape(50,50)
plt.imshow(a, cmap=plt.get_cmap(CMAP))

enter image description here

But if I make the array values homogenous, the plot is always the same dark blue value regardless of what the array's value is.

fig = plt.figure()
CMAP =  "seismic"   # blue-white-red colormap

#either of these two lines gives the same result
a = np.array([0.9]*50*50).reshape(50,50)
a = np.array([0.1]*50*50).reshape(50,50)

введите описание изображения здесь

Пока массив не имеет однородных значений, кажется, что он работает должным образом, например,

a = np.array([0.1,.9]*25*50).reshape(50,50)

рендеринг с полосами, как я предполагаю.

1 Ответ

2 голосов
/ 01 августа 2020

Чтобы увидеть, что происходит, полезно добавить цветную полосу рядом с изображением:

import numpy as np
import matplotlib.pyplot as plt

cmap =  "seismic"
a = np.random.rand(50,50)/2
plt.imshow(a, cmap=cmap)
plt.colorbar()
plt.show()

imshow random

Note that dark blue corresponds to the value 0 and dark red to 0.5.

The following shows what happens in the other cases:

fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(12, 3))
cmap = "seismic"

a = np.full((50,50), 0.9)
img1 = ax1.imshow(a, cmap=cmap)
plt.colorbar(img1, ax=ax1)

a = np.full((50,50), 0.1)
img2 = ax2.imshow(a, cmap=cmap)
plt.colorbar(img2, ax=ax2)

a = np.repeat([0.1,.9], 25*50).reshape(50,50)
img3 = ax3.imshow(a, cmap=cmap)
plt.colorbar(img3, ax=ax3)

3 subplots

When all data values are 0.9, matplotlib chooses a small range (in this case from 0.825 to 0.975) where the constant value 0.9 now corresponds to white. (Your example code seems to use an older version of matplotlib where the constant value corresponds to the darkest color). Something similar happens for the constant 0.1, with another range.

With half 0.1 and half 0.9, the range is set from 0.1 to 0.9, with 0.1 corresponding to dark blue and 0.9 to dark red.

These values are accessible via parameters, they are called vmin and vmax. When drawing many plots it can be interesting to use the same vmin and vmax for all of them. Here are the same examples, but with imshow(..., vmin=0, vmax=1):

используя vmin = 0 vmax = 1

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...