Search code examples
python-3.xmatplotlibcolor-conversion

Convert matplotlib color value to RGB


I want to convert color value in this format ((0.19215686274509805, 0.5098039215686274, 0.7411764705882353)) to RGB value.

I tried the following,

    import matplotlib
    from matplotlib import pyplot as plt

    cycler = plt.cycler("color", plt.cm.tab20c.colors)()

    color = next(cycler)['color']
    color_rgb = matplotlib.colors.to_rgb(color) # <--

The last line, to_rgb(color) doesn't work.

Any suggestions?


Solution

  • The problem you describe is that your statement:

    The last line, to_rgb(color) doesn't work.

    is not true.

    As OrOrg already commented:

    to_rgb(c) converts whatever c is (can be many things as long as it relates to color: a hex string, name, ...) into an RGB tuple with values in the range [0,1]. But in your case c is already an RGB tuple, so nothing extra happens.

    What you expect is to get the RGB values as integers or a string with a hex-code what can be done as follows:

    from matplotlib import pyplot as plt
    
    cycler = plt.cycler("color", plt.cm.tab20c.colors)()
    color = next(cycler)["color"]
    
    color_rgb = tuple([int(c*255) for c in color])  # <--
    print(color_rgb)     # gives (49, 130, 189)
    color_rgb_hex = '#%02x%02x%02x' % color_rgb     # <--
    print(color_rgb_hex) # gives '#3182bd'
    

    The matplotlib .to_hex() works as by you expected :

    color_rgb_hex_by_matplotlib = matplotlib.colors.to_hex(color)
    print(color_rgb_hex_by_matplotlib) # gives '#3182bd'
    

    The matplotlib .to_rgb() drops only the alpha channel from the to it passed color see here