Get colors from matplotlib style

Question:

What I would like to achieve:

I want to create several pie charts on one figure. They all share some categories but sometimes have different ones. Obviously I want all of the same categories to have the same colors.

That is why I created a dictionary which links the categories (= labels) to the colors. With that I can specify the colors of the pie chart. But I would like to use the ggplot color (which come with matplotlib.style.style.use(‘ggplot’)). How can I get those colors to feed them into my dictionary?

# set colors for labels
color_dict = {}
for i in range(0, len(data_categories)):
    color_dict[data_categories[i]] = ???

# apply colors
ind_label = 0
for pie_wedge in pie[0]:
    leg = ax[ind].get_legend()
    pie_wedge.set_facecolor(color_dict[labels_0[ind_label]])          
    leg.legendHandles[ind_label].set_color_(color_dict[labels_0[ind_label]])
    ind_label += 1
Asked By: cedi123

||

Answers:

Short answer

To access the colors used in the ggplot style, you can do as follows

In [37]: import matplotlib.pyplot as plt                                                  

In [38]: plt.style.use('ggplot')                                                          

In [39]: colors = plt.rcParams['axes.prop_cycle'].by_key()['color']                       

In [40]: print('n'.join(color for color in colors))                                      
#E24A33
#348ABD
#988ED5
#777777
#FBC15E
#8EBA42
#FFB5B8

In the above example the colors, as RGB strings, are contained in the list colors.

Remember to call plt.style.use(...) before accessing the color list, otherwise you’ll find the standard colors.


More detailed explanation

The answer above is tailored for modern releases of Matplotlib, where the plot colors and possibly other plot properties, like line widths and dashes (see this answer of mine) are stored in the rcParams dictionary with the key 'axes.prop_cycle' and are contained in a new kind of object, a cycler (another explanation of a cycler is contained in my answer referenced above).

To get the list of colors, we have to get the cycler from rcParams and then use its .by_key() method

Signature: c.by_key()
Docstring: Values by key

This returns the transposed values of the cycler.  Iterating
over a `Cycler` yields dicts with a single value for each key,
this method returns a `dict` of `list` which are the values
for the given key.

The returned value can be used to create an equivalent `Cycler`
using only `+`.

Returns
-------
transpose : dict
    dict of lists of the values for each key.

to have a dictionary of values that, at last, we index using the key 'color'.


Addendum
Updated, 2023-01-01.

It is not strictly necessary to use('a_style') to access its colors, the colors are (possibly) defined in a matplotlib.RcParams object that is stored in the dictionary matplotlib.style.library.
E.g., let’s print all the color sequences defined in the different styles

In [23]: for style in sorted(plt.style.library):
    ...:     the_rc = plt.style.library[style]
    ...:     if 'axes.prop_cycle' in the_rc:
    ...:         colors = the_rc['axes.prop_cycle'].by_key()['color']
    ...:         print('%25s: %s'%(style, ', '.join(color for color in colors)))
    ...:     else:
    ...:         print('%25s: this style does not modify colors'%style)
          Solarize_Light2: #268BD2, #2AA198, #859900, #B58900, #CB4B16, #DC322F, #D33682, #6C71C4
      _classic_test_patch: this style does not modify colors
             _mpl-gallery: this style does not modify colors
      _mpl-gallery-nogrid: this style does not modify colors
                      bmh: #348ABD, #A60628, #7A68A6, #467821, #D55E00, #CC79A7, #56B4E9, #009E73, #F0E442, #0072B2
                  classic: b, g, r, c, m, y, k
          dark_background: #8dd3c7, #feffb3, #bfbbd9, #fa8174, #81b1d2, #fdb462, #b3de69, #bc82bd, #ccebc4, #ffed6f
                     fast: this style does not modify colors
          fivethirtyeight: #008fd5, #fc4f30, #e5ae38, #6d904f, #8b8b8b, #810f7c
                   ggplot: #E24A33, #348ABD, #988ED5, #777777, #FBC15E, #8EBA42, #FFB5B8
                grayscale: 0.00, 0.40, 0.60, 0.70
                  seaborn: #4C72B0, #55A868, #C44E52, #8172B2, #CCB974, #64B5CD
           seaborn-bright: #003FFF, #03ED3A, #E8000B, #8A2BE2, #FFC400, #00D7FF
       seaborn-colorblind: #0072B2, #009E73, #D55E00, #CC79A7, #F0E442, #56B4E9
             seaborn-dark: this style does not modify colors
     seaborn-dark-palette: #001C7F, #017517, #8C0900, #7600A1, #B8860B, #006374
         seaborn-darkgrid: this style does not modify colors
             seaborn-deep: #4C72B0, #55A868, #C44E52, #8172B2, #CCB974, #64B5CD
            seaborn-muted: #4878CF, #6ACC65, #D65F5F, #B47CC7, #C4AD66, #77BEDB
         seaborn-notebook: this style does not modify colors
            seaborn-paper: this style does not modify colors
           seaborn-pastel: #92C6FF, #97F0AA, #FF9F9A, #D0BBFF, #FFFEA3, #B0E0E6
           seaborn-poster: this style does not modify colors
             seaborn-talk: this style does not modify colors
            seaborn-ticks: this style does not modify colors
            seaborn-white: this style does not modify colors
        seaborn-whitegrid: this style does not modify colors
     tableau-colorblind10: #006BA4, #FF800E, #ABABAB, #595959, #5F9ED1, #C85200, #898989, #A2C8EC, #FFBC79, #CFCFCF

In my understanding

  • the seaborn-xxx styles that do not modify colors are to be used as the last step in a sequence of styles, e.g., plt.style.use(['seaborn', 'seaborn-poster']) or plt.style.use(['seaborn', 'seaborn-muted', 'seaborn-poster'])
  • also the _ starting styles are meant to modify other styles, and
  • the only other style,fast, that does not modify the colors is all about tweaking the rendering parameters to have a faster rendering.
Answered By: gboffi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.