Matplotlib color bar for PatchCollection overrides colors

I draw patches according to the values ​​set in the values ​​of the variables.

pc = PatchCollection(patches, match_original=True)  

norm = Normalize()
cmap = plt.get_cmap('Blues')
pc.set_facecolor(cmap(norm(values)))
ax.add_collection(pc)

enter image description here

Now I also need an extra color panel. If I interject (e.g. before set_facecolor)

pc.set_array(values) # values
plt.colorbar(pc)

enter image description here

It works, but now all the colors have turned to shades of gray. The next one set_facecolordoesn’t change anything. Even when I add the command cmap=to plt.colorbar(), everything remains in the grayscale. I don’t know what to do with it.

+4
source share
1 answer

You are asking how to color a collection using a specific color map?

Just set the color code ( cmap) as well array.

For instance:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection

num = 10
data = np.random.random((num, 2))
values = np.random.normal(10, 5, num)

# I'm too lazy to draw irregular polygons, so I'll use circles
circles = [plt.Circle([x, y], 0.1) for (x,y) in data]
col = PatchCollection(circles)

col.set(array=values, cmap='jet')

fig, ax = plt.subplots()

ax.add_collection(col)
ax.autoscale()
ax.axis('equal')

fig.colorbar(col)
plt.show()

enter image description here

, :

(.. set_facecolors), (set_array), . . set_array .

+3

Source: https://habr.com/ru/post/1545369/


All Articles