Home > other >  Convert RGBA tuple to hex with matplotlib
Convert RGBA tuple to hex with matplotlib

Time:05-22

Conversion of rgb to hex is straightforward with matplotlib, but the alpha value seems to be ignored.

For example the output of the two are the same:

mpl.colors.rgb2hex((0.1, 0.1, 0.1, 0.1))
mpl.colors.rgb2hex((0.1, 0.1, 0.1, 0.8))

Which creates the same hex code (#1a1a1a), which isn't what I'd like. I'm not sure exactly which codes I would like - but I know I would like to be able to have a "lighter" hex code if the alpha value is lower.

Typically I might use an alpha parameter to control the lightness/saturation (sorry I don't have very good language for describing colours) - so it's important that I'm able to do so - but I need to be able to do so by converting RGBA tuples to hex.

CodePudding user response:

You need to specify keep_alpha=True:

mpl.colors.rgb2hex((0.1, 0.1, 0.1, 0.1), keep_alpha=True)
# out: #1a1a1a1a
mpl.colors.rgb2hex((0.1, 0.1, 0.1, 0.8), keep_alpha=True)
# out: #1a1a1acc
  • Related