How can I generate a colormap array from a simple array in matplotlib

前端 未结 1 1651
闹比i
闹比i 2020-12-16 20:44

In some functions of matplotlib, we have to pass an color argument instead of a cmap argument, like bar3d.

So we

相关标签:
1条回答
  • 2020-12-16 21:33

    The answer to your question is given in the snipplet of the documentation that you copied into your question:

    ...from the interval [0, 1] to the RGBA color...

    But if you find your code ugly you could try to make it nicer:

    1. You don't have to specify the limits to the normalization manually (iff you intent to use min/max):

      norm = plt.Normalize()
      colors = plt.cm.jet(norm(dz))
      
    2. If you find that ugly (I don't understand why, though), you could go on and do it manually):

      colors = plt.cm.jet(np.linspace(0,1,len(dz)))
      

      However this is solution is limited to equally spaced colors (which is what you want given the dz in your example.

    3. And then you can also replicate the functionality of Normalize (since you seem to not like it):

      lower = dz.min()
      upper = dz.max()
      colors = plt.cm.jet((dz-lower)/(upper-lower))
      
    4. Use a helper function:

      def get_colors(inp, colormap, vmin=None, vmax=None):
          norm = plt.Normalize(vmin, vmax)
          return colormap(norm(inp))
      

      Now you can use it like this:

      colors = get_colors(dz, plt.cm.jet)
      
    0 讨论(0)
提交回复
热议问题