从 matplotlib 样式中获取颜色 [英] Get colors from matplotlib style

查看:49
本文介绍了从 matplotlib 样式中获取颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的目标:

我想在一个图形上创建几个饼图.它们都共享某些类别,但有时有不同的类别.显然,我希望所有相同的类别都具有相同的颜色.

这就是为什么我创建了一个将类别(=标签)链接到颜色的字典的原因.这样,我可以指定饼图的颜色.但我想使用 ggplot 颜色(与 matplotlib.style.style.use('ggplot') 一起提供).如何获得这些颜色以将其输入到字典中?

 #设置标签的颜色color_dict = {}对于范围内的 i(0, len(data_categories)):color_dict [data_categories [i]] = ???# 应用颜色ind_label = 0对于pie [0]中的pie_wedge:腿=斧[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

解决方案

简短答案

要访问ggplot样式中使用的颜色,您可以执行以下操作

 在[37]中:将matplotlib.pyplot导入为plt在[38]中:plt.style.use('ggplot')在[39]中:颜色= plt.rcParams ['axes.prop_cycle'].by_key()['color']在 [40]: print('\n'.join(color for color in colors))#E24A33#348ABD#988ED5#777777#FBC15E#8EBA42#FFB5B8

在上面的示例中,颜色以RGB字符串的形式包含在列表 colors 中.

在访问颜色列表之前,请记住先调用 plt.style.use(...),否则您将找到标准颜色.

<小时>

更详细的解释

上面的答案是为 Matplotlib 的现代版本量身定制的,其中绘图颜色和可能的其他绘图属性,如线宽和破折号(参见 我的这个答案) 存储在 rcParams 字典中,键为 'axes.prop_cycle' 并包含在一种新的对象中,一个 <一个href ="https://matplotlib.org/cycler/" rel ="noreferrer"> cycler (有关 cycler 的另一种解释,上面提到的答案).

要获取颜色列表,我们必须从 rcParams 获取 cycler ,然后使用其 .by_key()方法<块引用>

 签名:c.by_key()Docstring:按键值这将返回循环仪的转置值.迭代在"Cycler"上产生的每个键具有单个值的字典,该方法返回"list"的"dict",即"list"的值对于给定的键.返回值可用于创建等效的`Cycler`只使用`+`.退货-------转置:dict每个键的值列表的字典.

有一个值的字典,最后,我们使用键'color'进行索引.

<小时>

附录

use('a_style') 访问其颜色并不是绝对必要的,颜色(可能)是在存储的 matplotlib.RcParams 对象中定义的在字典 matplotlib.style.library 中.例如,让我们打印以不同样式定义的所有颜色序列

 在[23]中:用于plt.style.library中的样式:...: the_rc = plt.style.library[style]...:如果the_rc中的"axes.prop_cycle":...:颜色= the_rc ['axes.prop_cycle'].by_key()['color']...: 打印('%25s: %s'%(style, ', '.join(color for color in colors)))...:     别的:...: print('%25s: 此样式不修改颜色'%style)dark_background:#8dd3c7,#feffb3,#bfbbd9,#fa8174,#81b1d2,#fdb462,#b3de69,#bc82bd,#ccebc4,#ffed6fggplot:#E24A33,#348ABD,#988ED5,#777777,#FBC15E,#8EBA42,#FFB5B8seaborn-poster:此样式不修改颜色seaborn-talk:此样式不会修改颜色seaborn-bright:#003FFF、#03ED3A、#E8000B、#8A2BE2、#FFC400、#00D7FFseaborn-notebook:此样式不修改颜色seaborn-darkgrid:此样式不会修改颜色bmh:#3​​48ABD、#A60628、#7A68A6、#467821、#D55E00、#CC79A7、#56B4E9、#009E73、#F0E442、#0072B2快速:此样式不修改颜色seaborn:#4C72B0、#55A868、#C44E52、#8172B2、#CCB974、#64B5CD浅白色:这种风格不会改变颜色_classic_test:b,g,r,c,m,y,k浅海深:#4C72B0,#55A868,#C44E52,#8172B2,#CCB974,#64B5CDseaborn-paper:此样式不修改颜色灰度:0.00、0.40、0.60、0.70seaborn-dark-palette:#001C7F,#017517,#8C0900,#7600A1,#B8860B,#006374seaborn-色盲:#0072B2、#009E73、#D55E00、#CC79A7、#F0E442、#56B4E9tableau-colorblind10:#006BA4,#FF800E,#ABABAB,#595959,#5F9ED1,#C85200,#898989,#A2C8EC,#FFBC79,#CFCFCFseaborn-dark:此样式不会修改颜色经典:b、g、r、c、m、y、kseaborn-pastel:#92C6FF、#97F0AA、#FF9F9A、#D0BBFF、#FFFEA3、#B0E0E6seaborn-ticks:此样式不会修改颜色Solarize_Light2:#268BD2、#2AA198、#859900、#B58900、#CB4B16、#DC322F、#D33682、#6C71C4seaborn-whitegrid:此样式不会修改颜色seaborn-muted:#4878CF,#6ACC65,#D65F5F,#B47CC7,#C4AD66,#77BEDB五三十八:#008fd5、#fc4f30、#e5ae38、#6d904f、#8b8b8b、#810f7c

PS——据我所知

  • 不修改颜色的 seaborn-xxx 样式将用作样式序列的最后一步,例如 plt.style.use(['seaborn','seaborn-poster']) plt.style.use(['seaborn','seaborn-muted','seaborn-poster'])
  • 唯一不更改颜色的其他样式 fast 都是关于调整渲染参数以使其具有更快渲染.

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

解决方案

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

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

PS — 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'])
  • the only other style,fast, that does not modify the colors is all about tweaking the rendering parameters to have a faster rendering.

这篇关于从 matplotlib 样式中获取颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆