Adding a matplotlib colorbar from a PatchCollection

冷暖自知 提交于 2019-12-05 17:11:46

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

There is no need to create an additional list. Assuming you work in pandas or numpy arrays.

For example:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib import cm

fig, ax = plt.subplots()
for c_l ,patches in dict_mapindex_mpl_polygon.items():
    color = df_map_elements.loc[c_l, 'stress_level']
    p = PatchCollection(patches,color=cm.Set2(color),lw=.3,edgecolor='k')
    ax.add_collection(p)
ax.autoscale_view()

p.set(array=df_map_elements['stress_level'].values, cmap='Set2')

fig.colorbar(p, label="Stress (index)")

plt.show()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!