pythonmatplotlibcolor-mapping

Getting a sample color in matplotlib


Is it possible to get an idea of what the color will appear in a plot by supplying the original RGB value (or other colormaps like RdYlBu) in python? Currently I have to really first convert a float number using cm.RdYlBu(x) and make a plot to see how the colors show up. But is there a quick way to check the color? Not necessarily in python, but any website that takes the value and returns the color according to the colormap would be fine.


Solution

  • Quick check in python console

    You may use python itself to quickly show a figure with the respective color from the matplotlib colormap.

    E.g. write a function

    def c(x):
       col = plt.cm.RdYlBu(x)
       fig, ax = plt.subplots(figsize=(1,1))
       fig.set_facecolor(col)
       ax.axis("off")
       plt.show()
    

    and then call it with the number of interest, e.g. c(0.4).

    Example how that looks in a jupyter console:

    enter image description here

    A colormap viewer

    Of course one could also write some color map viewer with matplotlib. For example:

    enter image description here

    import sys
    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.widgets
    
    class CMViewer():
        def __init__(self, cmap, valinit=0.5):
            self.cmap = plt.get_cmap(cmap)
            col = self.cmap(valinit)
            self.fig, axes = plt.subplots(nrows=4, figsize=(5,3), num=cmap,
                                          gridspec_kw={"height_ratios" : [0.3,1,1,1]})
            self.fig.subplots_adjust(right=0.85)
            self.sliderax, self.cax, self.fax, self.lax = axes
            
            self.slider = matplotlib.widgets.Slider(self.sliderax, cmap, 0., 1., 
                                                    valinit=valinit)
            self.slider.on_changed(self.update)
            self.slider.vline.set_color("k")
            
            x = np.linspace(0.,1.,256)
            self.cax.imshow(x[np.newaxis, :], cmap=cmap, aspect="auto")
            ta = dict(axis="both", bottom=0, left=0, labelbottom=0, labelleft=0)
            self.cax.tick_params(**ta)
            self.fax.tick_params(**ta)
            self.lax.tick_params(**ta)
            
            x = np.array([0,0,1,2,2])
            self.lax.imshow(x[np.newaxis, :], cmap="gray", aspect="auto", 
                            extent=[0,1,-0.2,1.2])
            self.lines = []
            for i in range(5):
                line = self.lax.plot([0,1],[i/4.,i/4.], alpha=0.2+i/5., color=col)[0]
                self.lines.append(line)
            
            self.update(0)
            plt.show()
            
        def fmtcol(self, col):
            return "{:.3f}  |  {:.3f}  |  {:.3f}".format(*col)
    
        def update(self, val):
            x = self.slider.val
            col = self.cmap(x)
            self.fax.set_facecolor(col)
            for line in self.lines:
                line.set_color(col)
            self.slider.poly.set_color(col)
            self.slider.vline.set_xdata(x)
            self.lax.set_xlabel(self.fmtcol(col))
            self.fig.canvas.draw_idle()
    
    if __name__ == "__main__":
        if len(sys.argv) > 1:     
            CMViewer(sys.argv[1])
        else:
            CMViewer("RdYlBu")
    

    If this is saved as CMViewer.py it could be run as script like

    > python CMViewer.py 
    

    or with a colormap specified,

    > python CMViewer.py viridis