Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Plotting colored grid based on values

I have been searching here and on the net. I found somehow close questions/answers to what I want, but still couldn't reach to what I'm looking for.

I have an array of for example, 100 values. The values are in the range from 0 to 100. I want to plot this array as a grid, filling the squares according to the values in the array.

The solutions I found so far are like the followings:

Drawing grid pattern in matplotlib

and

custom matplotlib plot : chess board like table with colored cells

In the examples I mentioned, the ranges of the colors vary and are not fixed.

However, what I am wondering about, is whether I can set the ranges for specific values and colors. For example, if the values are between 10 and 20, let the color of the grid square be red. else if the values are between 20 and 30, let the color be blue. etc.

How this could be achieved in python?

like image 537
philippos Avatar asked May 15 '17 03:05

philippos


People also ask

How do you shade part of a graph in Python?

MatPlotLib with Python To shade an area parallel to X-axis, initialize two variables, y1 and y2. To add horizontal span across the axes, use axhspan() method with y1, y2, green as shade color,and alpha for transprency of the shade. To display the figure, use show() method.

What does PLT grid () do in Python?

grid() Function. The grid() function in pyplot module of matplotlib library is used to configure the grid lines.


1 Answers

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; Plot with BoundaryNorms

For more, you can check this matplotlib example.

like image 57
umutto Avatar answered Oct 11 '22 01:10

umutto