Peter B
Peter B

Reputation: 493

python matplotlib: retrieving colors used in contour plot

I make a contour map with (say) 10 contours, like this:

CS = plt.contour(X, Y, Z, levels=levels)

Where levels is a list of 10 numbers.

I'm pretty happy with the colors that matplotlib uses - I think it chooses 10 nicely spaced colors from the default color map - but how do I retrieve the actual colors used? (Like as a list of RGB values). The reason is I'd like to build a custom color bar (by using those colors in plt.hlines commands).

Upvotes: 4

Views: 1503

Answers (2)

innisfree
innisfree

Reputation: 2485

Worth noting: the object returned by contourf has a get_cmap method, so

   cf = plt.contourf( ... )
   cmap = cf.get_cmap()
   colors = cmap(np.linspace(0, 1, 10))

might be useful.

Upvotes: 2

CT Zhu
CT Zhu

Reputation: 54340

Say if you want 10 levels, of the color map jet:

import matplotlib.cm as cm

cm.jet(np.linspace(0, 1, 10))
Out[31]: 
array([[ 0.        ,  0.        ,  0.5       ,  1.        ],
       [ 0.        ,  0.        ,  0.99910873,  1.        ],
       [ 0.        ,  0.37843137,  1.        ,  1.        ],
       [ 0.        ,  0.83333333,  1.        ,  1.        ],
       [ 0.30044276,  1.        ,  0.66729918,  1.        ],
       [ 0.66729918,  1.        ,  0.30044276,  1.        ],
       [ 1.        ,  0.90123457,  0.        ,  1.        ],
       [ 1.        ,  0.48002905,  0.        ,  1.        ],
       [ 0.99910873,  0.07334786,  0.        ,  1.        ],
       [ 0.5       ,  0.        ,  0.        ,  1.        ]])

The return is an array of RGBA values.

Upvotes: 5

Related Questions