Adding a matplotlib colorbar from a PatchCollection

2024/11/13 8:47:31

I'm converting a Shapely MultiPolygon to a PatchCollection, and first colouring each Polygon like so:

# ldn_mp is a MultiPolygon
cm = plt.get_cmap('RdBu')
num_colours = len(ldn_mp)fig = plt.figure()
ax = fig.add_subplot(111)
minx, miny, maxx, maxy = ldn_mp.bounds
w, h = maxx - minx, maxy - miny
ax.set_xlim(minx - 0.2 * w, maxx + 0.2 * w)
ax.set_ylim(miny - 0.2 * h, maxy + 0.2 * h)
ax.set_aspect(1)patches = []
for poly in ldn_mp:colour = cm(1. * len(filter(poly.contains, points)) / num_colours)patches.append(PolygonPatch(poly, fc=colour, ec='#555555', lw=0.2, alpha=1., zorder=1))
pc = PatchCollection(patches, match_original=True)
ax.add_collection(pc)
ax.set_xticks([])
ax.set_yticks([])
plt.title("Density of NO$^2$ Sensors by Borough")
plt.tight_layout()
plt.show()

But I'd like to add a colorbar to my plot, based upon the PatchCollection colors. I'm not sure how to go about that; do I pass the cmap keyword when creating pc? How do I then call set_array() with the colours I've used?

Answer

I had the same problem a little while ago. For each polygon I saved the corresponding color to a list named mycolors:

mycolors=[]
...
mycolors.append(SSTvalue)
path_patch = patches.PathPatch(mypath, lw=1)
mypatches.append(path_patch)

I looped over a series of multipolygons stored in a Shapefile and stored each patch in a collection. After that I plotted the polygons using the color information I had stored in the list, which was converted to an array eventually, and added a colorbar:

p = PatchCollection(mypatches, cmap=plt.get_cmap('RdYlBu_r'), alpha=1.0)
p.set_array(array(mycolors))
p.set_clim([np.ma.min(mycolors),np.ma.max(mycolors)])
plt.colorbar(p,shrink=0.5)

The full script I used to plot temperature values with colors and a colorbar for large marine ecosystems of the world represented by polygons can be found here. Hope this helps. Cheers, Trond

https://en.xdnf.cn/q/72190.html

Related Q&A

Mac 10.6 Universal Binary scipy: cephes/specfun _aswfa_ symbol not found

I cant get scipy to function in 32 bit mode when compiled as a i386/x86_64 universal binary, and executed on my 64 bit 10.6.2 MacPro1,1.My python setupWith the help of this answer, I built a 32/64 bit …

python: numpy list to array and vstack

from scipy.io.wavfile import read filepath = glob.glob(*.wav) rates = [] datas = [] for fp in filepath:rate, data = read(fp)rates.append(rate)datas.append(data)I get a list datas which is :[array([0, 0…

Django Unittests Client Login: fails in test suite, but not in Shell

Im running a basic test of my home view. While logging the client in from the shell works, the same line of code fails to log the client in when using the test suite.What is the correct way to log the …

Icon overlay issue with Python

I found some examples and topics on this forum about the way to implement an icon overlay handler with Python 2.7 & the win32com package but it does not work for me and I dont understand why. I cre…

Comparing NumPy object references

I want to understand the NumPy behavior.When I try to get the reference of an inner array of a NumPy array, and then compare it to the object itself, I get as returned value False.Here is the example:I…

Does using django querysets in templates hit the database?

Do template value tags force django to hit the database when called against a non-context value? For example:{{ request.user.username }} Is the call to show the currently logged in users username. H…

how to randomly sample in 2D matrix in numpy

I have a 2d array/matrix like this, how would I randomly pick the value from this 2D matrix, for example getting value like [-62, 29.23]. I looked at the numpy.choice but it is built for 1d array.The f…

How to update figure in same window dynamically without opening and redrawing in new tab?

I am creating a 3D scatter plot based off a pandas dataframe, and then I want to re-draw it with slightly updated data whenever the user presses a button in my program. I almost have this functionality…

Serializing a C struct in Python and sending over a socket

Im trying to serializing the following C structstruct packet {int id;unsigned char *ce;unsigned char *syms; };in Python and send it over a socket. The number of elements pointed by ce and syms are know…

creating multiple audio streams of an icecast2 server using python-shout

I am trying to create a web radio server to stream 3 sources at once. I am using python to create a source client for icecast2 using the python-shout library. I am not too familiar with the language (p…