Color range adjustment in matplotlib patchcollection

I draw a PatchCollection in matplotlib with the coordinates and color values โ€‹โ€‹of the patch read from the file.

The problem is that matplotlib seems to automatically scale the range of colors to the minimum / maximum values โ€‹โ€‹of the data. How can I manually set the color range? For example. if my data range is 10-30, but I want to scale it to a color range of 5-50 (for example, to compare with another plot), how can I do this?

My build commands look the same as in the api code example: patch_collection.py

 colors = 100 * pylab.rand(len(patches)) p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4) p.set_array(pylab.array(colors)) ax.add_collection(p) pylab.colorbar(p) pylab.show() 
+7
source share
1 answer

Use p.set_clim([5, 50]) to set minima and maxima for color scaling for your example. Everything that matplotlib has, which has a color palette, has get_clim and set_clim .

As a complete example:

 import matplotlib import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches import Circle import numpy as np # (modified from one of the matplotlib gallery examples) resolution = 50 # the number of vertices N = 100 x = np.random.random(N) y = np.random.random(N) radii = 0.1*np.random.random(N) patches = [] for x1,y1,r in zip(x, y, radii): circle = Circle((x1,y1), r) patches.append(circle) fig = plt.figure() ax = fig.add_subplot(111) colors = 100*np.random.random(N) p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4) p.set_array(colors) ax.add_collection(p) plt.colorbar(p) plt.show() 

enter image description here

Now, if we just add p.set_clim([5, 50]) (where p is the collection of patches) somewhere before we call plt.show(...) , we get the following: enter image description here

+20
source

All Articles