Python - Plotting colored grid based on values

本小妞迷上赌 提交于 2019-11-28 23:36:58

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

import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np

data = np.random.rand(10, 10) * 20

# create discrete colormap
cmap = 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 gridlines
ax.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;

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!