pythonmatplotlibcolorbarcolor-mapping

Setting the size of a matplotlib ColorbarBase object


I have an patch collection that I'd like to display a color map for. Because of some manipulations I do on top of the colormap, it's not possible for me to define it using a matplotlib.colorbar instance. At least not as far as I can tell; doing so strips some manipulations I do with my colors that blank out patches lacking data:

cmap = matplotlib.cm.YlOrRd
colors = [cmap(n) if pd.notnull(n) else [1,1,1,1]
          for n in plt.Normalize(0, 1)([nullity for _, nullity in squares])]

# Now we draw.
for i, ((min_x, max_x, min_y, max_y), _) in enumerate(squares):
    square = shapely.geometry.Polygon([[min_x, min_y], [max_x, min_y],
                                      [max_x, max_y], [min_x, max_y]])
    ax0.add_patch(descartes.PolygonPatch(square, fc=colors[i], 
                  ec='white', alpha=1, zorder=4))

So I define a matplotlib.colorbar.ColorbarBase instance instead, which works:

matplotlib.colorbar.ColorbarBase(ax1, cmap=cmap, orientation='vertical',
                                 norm=matplotlib.colors.Normalize(vmin=0, vmax=1))

Which results in e.g.:

enter image description here

The problem I have is that I want to reduce the size of this colorbar (specifically, the shrink it down to a specific vertical size, say, 500 pixels), but I don't see any obvious way of doing this. If I had a colorbar instance, I could adjust this easily using its axis property arguments, but ColorbarBase lacks these.

For further reference:


Solution

  • The size and shape is defined with the axis. This is a snippet from code I have where I group 2 plots together and add a colorbar at the top independently. I played with the values in that add_axes instance until I got a size that worked for me:

     cax = fig.add_axes([0.125, 0.925, 0.775, 0.0725]) #has to be as a list - starts with x, y coordinates for start and then width and height in % of figure width
     norm = mpl.colors.Normalize(vmin = low_val, vmax = high_val)     
     mpl.colorbar.ColorbarBase(cax, cmap = self.cmap, norm = norm, orientation = 'horizontal')