bioslime bioslime - 24 days ago 15
Python Question

Matplotlib colorbar for PatchCollection overrides colors

I am plotting patches according to values set in the variable values.

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 want an additional colorbar. 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 colors have turned to a greyscale. The following
set_facecolor
does not change anything. Even when i add a
cmap=
command in the
plt.colorbar()
everything remains in the greyscale. I have no clue what to do about it.

Answer

Are you asking how to color a collection by a specific colormap?

Just set the colormap (cmap) as well as the array.

For example:

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

To explain what's going on in your question:

For collections, the facecolors are either manually set (i.e. set_facecolors) or they're colormapped to a range of values (set_array) controlled by a colorbar. These two options are mutually exclusive. Therefore, after you call set_array, the original facecolors are ignored.

Comments