简体   繁体   中英

Setting color for specific value in Matplotlib imshow

Suppose that i'm plotting the following numpy array of data on a simple matplotlib heatmap using imshow ; there are some cases where the value will be 0.0 . Is there any way to set a specif color for the cell where that value will be shown? For example, when the value is 0, the color for that cell must be black

a = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
              [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
              [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
              [0.6, 0.0, 0.3, 0.0, 0, 0.0, 0.0],
              [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
              [0, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
              [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])   

Map = ax.imshow(a, interpolation='none', cmap='coolwarm')

Maybe not the perfect solution, but definitely a simple one. If it is only for the purpose of creating an image you can modify the original data (or a copy of it) and replace 0.0 with NaN . Then you can use set_bad to get the desired output.

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

a = np.array([[0.8, 2.4, -2.5, 3.9, 0.0, 4.0, 0.0],
              [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
              [-1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
              [0.6, 0.0, 0.3, 0.0, 0, 0.0, 0.0],
              [0.7, 1.7, -0.6, 2.6, 2.2, 6.2, 0.0],
              [0, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
              [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])   

c_map = cm.get_cmap('rainbow')
c_map.set_bad('k')
b = a.copy()
b[b==0] = np.nan
fig = plt.imshow(b, interpolation='none', cmap=c_map)
plt.colorbar(fig)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM