Colorbars for mixed usage of colormaps and static colors

In case you want to show colormapped data with matplotlib and you use code similar to this one:

plt.scatter(xs, ys, c=vals, cmap='PuBu', s=20)
plt.scatter(xs1, ys1, c='red', cmap=None, s=30)
plt.colorbar()

you will get the following error.

Traceback (most recent call last):
  File "generate.py", line 46, in <module>
    plt.colorbar()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/pyplot.py", line 1694, in colorbar
    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/figure.py", line 1209, in colorbar
    cb = cbar.Colorbar(cax, mappable, **kw)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/colorbar.py", line 718, in __init__
    mappable.autoscale_None() # Ensure mappable.norm.vmin, vmax
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/cm.py", line 282, in autoscale_None
    raise TypeError('You must first set_array for mappable')
TypeError: You must first set_array for mappable

This is because the colorbar method draws the last colormap used, which is given as a None default argument to plt.scatter. Therefore, making the calls to plt.scatter in the order given in the example above overwrites the colorbar value internally at sets it to None, which gives the error mentioned above. Make sure that the last plt.anything function is called with an appropriate cmap argument just before you add the plt.colorbar.

You may also like...

Leave a Reply

Your email address will not be published.