0

I created a function that is a wrap around matplotlib imshow that basically add a proper colorbar when I show a RGBA image (for which the cmap parameter is ignored) This is how I create the colormap

    import matplotlib.colors as mcol
    from matplotlib import cm

    start_hue, stop_hue = 0, 360 # this is used to evnt. select only a subset of the available colors in the HSV colorspace. Specific values are not particularly relevant for my question
    vmin, vmax = 0, np.pi/2  # example
    color_range = np.arange(start_hue, stop_hue) / 360
    hsv_cmap = cm.get_cmap('hsv')
    cmap = mcol.ListedColormap(hsv_cmap(color_range))
    cbar_mappable= cm.ScalarMappable(cmap=cmap)
    cmap.set_clim(vmin=vmin, vmax=vmax)

Then I add the colorbar to a Figure instance containing my imshow plot

    cax = plt.axes([0.87, 0.1, 0.025, 0.8])
    fig.colorbar(cbar_mappable, cax=cax) 

Everything looks fine. When I plot the image with my function the colorbar shows the right colors and the correct vmin, vmax values I set for it. However,I tried the same code on a different computer and I got the error:

    TypeError: You must first set_array for mappable 

So to solve this I simply do:

    cbar_mappable.set_array(my_rgba_nparray)

Questions

  1. is my approach correct? is it ok to use the RGBA array for set_array() ?
  2. why do I need to use set_array()? Isn't it already set when I do
    cmap = mcol.ListedColormap(hsv_cmap(color_range)) ?
  1. why is on one computer working just fine even if I DO NOT use set_array()? What should I check to find out why there is this different behavior on different machines?
Robyc
  • 379
  • 1
  • 13
  • Usually one sets an empty array `cbar_mappable.set_array([])`. See [Matplotlib ScalarMappable: why need to set_array() if norm set?](https://stackoverflow.com/questions/28801803/matplotlib-scalarmappable-why-need-to-set-array-if-norm-set/49036899). The error message seems to be fixed since matplotlib 3.1.0, so an idea is to upgrade matplotlib on the computers where you want to run this. – JohanC Jun 08 '20 at 10:22
  • Different results on different computer because of different Matplotlib versions, starting from 3.1 they fixed this problem... – gboffi Jun 08 '20 at 12:31
  • It is just very counter-intuitive (actually it looks totally wrong) that I need to set an empty array to a colormap that already has the right values. But if that is just a workaround for a matplotlib issue than I'm happy with the answer. Thanks – Robyc Jun 08 '20 at 13:11
  • So my doubt was: if mpl asks me to use set_array() then maybe I didn't use the right procedure to set the array of values for the colormap? Hence, my question here on stackoverflow (specifically, question 1) – Robyc Jun 08 '20 at 13:12

0 Answers0