Miguel Gonzalez
Miguel Gonzalez

Reputation: 773

Set cmap to a Matplotlib PatchCollection

I have a Patch Collection conformed by several polygons (triangles). Each of that triangle have associated an integer value. I would like to set a color map to that Patch Collection based on the different values of the triangles.

This is my code:

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

X = np.linspace(0,10,5)
Y = np.linspace(0,10,5)
values = [np.random.randint(0,5) for i in range(0,5)]

fig, ax = plt.subplots()

s = 2   # Triangle side
patches = []

# Creating patches --> How could I insert here 'value' variable? For taking it into account in cmap.
for x,y,value in zip(X,Y,values):
    tri = matplotlib.patches.Polygon(([(x      ,       y     ),
                                       (x + s/2, y - 0.866 * s),
                                       (x - s/2, y - 0.866 * s)]),
                                    lw = 2, edgecolor='black')
    patches.append(tri)

coll = matplotlib.collections.PatchCollection(patches, match_original = True)
ax.add_collection(coll)

ax.set_xlim(1,12)
ax.set_ylim(0,12)

plt.show()

Does anyone know how could I do this?

Upvotes: 1

Views: 1264

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150755

This instruction seems to translate to your case pretty well:

# values as numpy array
values = np.array([np.random.randint(0,5) for i in range(0,5)])

# define the norm 
norm = plt.Normalize(values.min(), values.max())
coll = matplotlib.collections.PatchCollection(patches, cmap='viridis',
                                              norm=norm, match_original = True)

coll.set_array(values)
polys = ax.add_collection(coll)
fig.colorbar(polys)

Output:

enter image description here

Upvotes: 3

Related Questions