5

I have a sequence of 3 (or more) colors stored as RGB values (or corresponding hex) and I would like to display them as below:

enter image description here

Following and modifying the suggestions here I was able to get somewhat close, though I am not quite sure I understand how colors are being represented there as a single float. Is there anyway I can convert an RGB/hex representation to whatever matshow() uses? Alternatively, is there a more elegant way of producing the above output? Thanks!

Community
  • 1
  • 1
Everaldo Aguiar
  • 4,016
  • 7
  • 26
  • 31

1 Answers1

4

There is a wrapper called seaborn that sits on top of matplotlib that does nice job of displaying the colormap or selected colors. For example:

sns.palplot(sns.color_palette("coolwarm", 7))

enter image description here

I suggest this over standard matplotlib since it exposes more support for working with color schemes and conversions as mentioned in the other part of your question. If you don't want to use an outside library, just modify the source code that plots this:

def palplot(pal, size=1):
    """Plot the values in a color palette as a horizontal array.

    Parameters
    ----------
    pal : sequence of matplotlib colors
        colors, i.e. as returned by seaborn.color_palette()
    size :
        scaling factor for size of plot

    """
    n = len(pal)
    f, ax = plt.subplots(1, 1, figsize=(n * size, size))
    ax.imshow(np.arange(n).reshape(1, n),
              cmap=mpl.colors.ListedColormap(list(pal)),
              interpolation="nearest", aspect="auto")
    ax.set_xticks(np.arange(n) - .5)
    ax.set_yticks([-.5, .5])
    ax.set_xticklabels([])
    ax.set_yticklabels([])
Hooked
  • 84,485
  • 43
  • 192
  • 261
  • That output looks great and thanks for the reference to this module (which seems very useful!). Is there a way to explicitly pass a sequence of colors to this function and have it plot them as opposed to selecting a color palette? Nevermind! I think I got it. Great suggestion. Thank yoU! – Everaldo Aguiar Feb 18 '14 at 18:24
  • 1
    @EveraldoAguiar I'm not sure off the top of my head, but you can use the posted code for `palplot` and feed the `ListedColormap` and discrete series of rgb colors. If you do that, make sure that you set the number of "boxes" equal to the size of the input, this function interpolates. – Hooked Feb 18 '14 at 18:26
  • you are relying on some auto-scale magic, it is better to use `set_xlim` and `set_ylim` directly. – tacaswell Feb 18 '14 at 18:40
  • @tcaswell "you are relying" => "seaborn authors are relying". This was copied directly off the source code (see link in answer). I posted it here to give the OP a starting point, though you recommendation is a good one - perhaps [open an issue](https://github.com/mwaskom/seaborn/issues)? – Hooked Feb 18 '14 at 18:44
  • ah, didn't fully grok the code provonence. You should adjust your answer either way ;) – tacaswell Feb 18 '14 at 18:58