Home > Enterprise >  Extract the color ID in matplotlib
Extract the color ID in matplotlib

Time:06-16

I am using tab20 colormap of matplotlib library and generated ten distinct colors in the following way:

cm = plt.get_cmap('tab20')
cy = cycler('color', [cm(1.*i/10)
                      for i in range(10)])  

If I type cy[0] I do not get the first color. I get the error

"Can only use slices with Cycler.__getitem__".

I need to extract the colors based on the indices. Is there a way to do that?

CodePudding user response:

Cycler doesn't support get value by index. You can use slicing to get the values in this manner:

color_cycle[:1] ##Will output first Color
color_cycle[1:2] ##Will output Second Color

For example for cy = cycler('color', [1, 2, 3, 4, 5]) the output of color_cycle[:1] will be cycler('color', [1])

CodePudding user response:

You can process like this:

import matplotlib.pyplot as plt
import numpy as np

cm = plt.get_cmap('tab20')
colors = cm(np.linspace(0, 1, 10))

print(colors[0])

gives array([0.12156863, 0.46666667, 0.70588235, 1. ])

In case you don't know the numpy module, np.linspace helps to create 10 evenly space values between, here, 0 and 1. You could also do:

print(cm(0.5))
>>> (0.5490196078431373, 0.33725490196078434, 0.29411764705882354, 1.0)

or

print(cm(0.3))
>>> (0.8392156862745098, 0.15294117647058825, 0.1568627450980392, 1.0)
  • Related