Python Matplotlib add Colorbar

11,987

As mentioned in the comments above, i would think twice about mixing Basemap and Cartopy, is there a specific reason to do so? Both are basically doing the same thing, extending Matplotlib with geographical plotting capabilities. Both are valid to use, they both have their pro's and con's.

In your example you have a Basemap axes m, a Cartopy axes ax and you are using the Pylab interface by using plt. which operates on the currently active axes. Perhaps it theoretically possible, but it seems prone to errors to me.

I cant modify your example to make it work, since the data is missing and your code is not valid Python, the indentation for the function is incorrect for example. But here is a Cartopy-only example showing how you can plot a Shapefile and use the same cmap/norm combination to add a colorbar to the axes.

One difference with your code is that you provide the axes containing the map to the ColorbarBase function, this should be a seperate axes specifically for the colorbar.

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib as mpl
import cartopy.io.shapereader as shpreader

fig, ax = plt.subplots(figsize=(12,6), 
                       subplot_kw={'projection': ccrs.PlateCarree()})

norm = mpl.colors.Normalize(vmin=0, vmax=1000000)
cmap = plt.cm.RdYlBu_r

for n, country in enumerate(shpreader.Reader(r'D:\ne_50m_admin_0_countries_lakes.shp').records()):

    ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                      facecolor=cmap(norm(country.attributes['gdp_md_est'])),
                      label=country.attributes['name'])

ax.set_title('gdp_md_est')

cax = fig.add_axes([0.95, 0.2, 0.02, 0.6])
cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, spacing='proportional')
cb.set_label('gdp_md_est')

enter image description here

Share:
11,987
user3066027
Author by

user3066027

Updated on June 18, 2022

Comments

  • user3066027
    user3066027 almost 2 years

    i've got a problem using MatlobLib with "Custom" Shapes from a shapereader. Importing and viewing inserted faces works fine, but i'm not able to place a colorbar on my figure.

    I already tried several ways from the tutorial, but im quite sure there is a smart solution for this problem.

    maybe somebody can help me, my current code is attached below:

    from formencode.national import pycountry
    import itertools
    from matplotlib import cm, pyplot
    from matplotlib import 
    from mpl_toolkits.basemap import Basemap
    from numpy.dual import norm
    import cartopy.crs as ccrs
    import cartopy.io.shapereader as shpreader
    import matplotlib as mpl
    import matplotlib.colors as colors
    import matplotlib.mlab as mlab
    import matplotlib.pyplot as plt
    import numpy as np
    
    def draw_map_for_non_normalized_data_with_alpha2_counrty_description(data, title=None):
    
    m = Basemap()
    ax = plt.axes(projection=ccrs.PlateCarree())
    
    list = []
    sum = 0
    for key in data:
        sum += data[key]
    
    for key in data.keys():
        new_val = (data[key]+0.00)/sum
        list.append(new_val)
        data[key] = new_val
    
    #===========================================================================
    # print str(min(list))
    # print str(max(list))
    #===========================================================================
    
    cmap = mpl.cm.cool
    colors = matplotlib.colors.Normalize(min(list)+0.0, max(list)+0.0)
    
    labels = []
    features = []
    for country in shpreader.Reader(shapename).records():
        a3_code = country.attributes["gu_a3"]
        try :
            a2_code =  pycountry.countries.get(alpha3=a3_code).alpha2
        except:
            a2_code = ""
    
        if a2_code in data:
            val = data[a2_code]
    
            color = cm.jet(norm(val))
    
            print str(val) + " value for color: " + str(color)
    
            labels.append(country.attributes['name_long'])
            feat = ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=color, label=country.attributes['name_long'])
    
            features.append(feat)   
    #ax.legend(features, labels, loc='upper right')
    #===========================================================================
    # fig = pyplot.figure(figsize=(8,3))    
    # ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
    #===========================================================================
    
    #cbar = m.colorbar(location='bottom')
    cb1 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,norm=colors,orientation='horizontal')
    cb1.set_label('foo')
    
    m.drawcoastlines()
    m.drawcountries()
    if title:
        plt.title(title)
    
    plt.show() 
    

    as you can see inside the code, i already tried several ways, but none of them worked for me.

    maybe somebody has "the" hint for me.

    thanks for help,

    kind regards

  • user3066027
    user3066027 over 9 years
    thanks a lot.. hmm the code might be mixed up during copy & paste. thanks for your example! as it works it is fine for me, i'm just looking for a simple way to do it and found just the way above described. i'll try it tonight :)
  • FaCoffee
    FaCoffee almost 7 years
    How do you move the colorbar closer to the plot? Mine is too far off.