bioslime bioslime - 1 year ago 178
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')

enter image description here

Now i also want an additional colorbar. If i interject (e.g. before set_facecolor)

pc.set_array(values) # values

enter image description here

it works, but now all colors have turned to a greyscale. The following
does not change anything. Even when i add a
command in the
everything remains in the greyscale. I have no clue what to do about it.

Answer Source

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()



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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download