Python - Plotting colored grid based on values Python - Plotting colored grid based on values python python

Python - Plotting colored grid based on values


You can create a ListedColormap for your custom colors and color BoundaryNorms to threshold the values.

import matplotlib.pyplot as pltfrom matplotlib import colorsimport numpy as npdata = np.random.rand(10, 10) * 20# create discrete colormapcmap = colors.ListedColormap(['red', 'blue'])bounds = [0,10,20]norm = colors.BoundaryNorm(bounds, cmap.N)fig, ax = plt.subplots()ax.imshow(data, cmap=cmap, norm=norm)# draw gridlinesax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)ax.set_xticks(np.arange(-.5, 10, 1));ax.set_yticks(np.arange(-.5, 10, 1));plt.show()

Resulting in;Plot with BoundaryNorms

For more, you can check this matplotlib example.


It depends on what units you need your colours to be in, but just a simple if statement should do the trick.

def find_colour(_val):    # Colour value constants    _colours = {"blue": [0.0, 0.0, 1.0],                "green": [0.0, 1.0, 0.00],                "yellow": [1.0, 1.0, 0.0],                "red": [1.0, 0.0, 0.0]}    # Map the value to a colour    _colour = [0, 0, 0]    if _val > 30:        _colour = _colours["red"]    elif _val > 20:        _colour = _colours["blue"]    elif _val > 10:        _colour = _colours["green"]    elif _val > 0:        _colour = _colours["yellow"]    return tuple(_colour)

And just convert that tuple to whatever units you need e.g. RGBA(..). You can then implement the methods it looks like you have already found to achieve the grid.