Retrieving Matplotlib Heatmap Colors
Solution 1:
You are looking for the colormap that is used by the image created via imshow
. Now of course you can reverse engineer how that colormap got into the image in the first place like the other answer suggests. That seems cumbersome and often enough isn't even possible.
So given an AxesImage
(the object returned by imshow
) or for that matter any other ScalarMappable
, you get the colormap in use via .cmap
. Since the data values are normalized to the range between 0..1, you need a normalization, which you get from the .norm
attribute. Finally, you need the data, which you get from the .get_array()
method.
The magic_function
is hence a chain of three functions.
im = plt.imshow(np.random.rand(10, 10))
color_matrix = im.cmap(im.norm(im.get_array()))
color_matrix
is now the (10, 10, 4)-shaped RGBA array of colors corresponding to the pixels in the image.
Solution 2:
Building upon this answer, you need to understand the default color map chosen by matplotlib
since you didn't provide one. The documentation states that it is the value of plt.rcParams["image.cmap"]
, so we use that.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from matplotlib.colors import Normalize
data = np.random.rand(10, 10)
cmap = cm.get_cmap(plt.rcParams["image.cmap"])
hm = plt.imshow(data)
norm = Normalize(vmin=data.min(), vmax=data.max())
rgba_values = cmap(norm(data))
The RGBA value of the upper left cell would then be rgba_values[0,0]
Post a Comment for "Retrieving Matplotlib Heatmap Colors"