python - 从 matplotlib 样式获取颜色

标签 python matplotlib

<分区>

我想实现的目标:

我想在一张图上创建多个饼图。他们都共享一些类别,但有时有不同的类别。显然,我希望所有相同的类别都具有相同的颜色。

这就是为什么我创建了一个将类别(= 标签)链接到颜色的字典。这样我就可以指定饼图的颜色。但我想使用 ggplot 颜色(matplotlib.style.style.use('ggplot') 附带)。我怎样才能将这些颜色输入到我的字典中?

# 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

最佳答案

简答

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

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

在上面的示例中,颜色作为 RGB 字符串包含在列表 colors 中。

记得在访问颜色列表之前调用plt.style.use(...),否则您会找到标准颜色。


更详细的解释

上面的答案是为现代版本的 Matplotlib 量身定制的,其中绘图颜色和可能的其他绘图属性,如线宽和破折号(参见 this answer of mine)存储在 rcParams 字典中key 'axes.prop_cycle' 并包含在一种新的对象中,一个 cycler (关于 cycler 的另一种解释包含在我上面引用的答案中)。

要获取颜色列表,我们必须从rcParams 获取cycler,然后使用它的.by_key() 方法

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.

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


附录
更新,2023 年 1 月 1 日。

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

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

我的理解

  • 不修改颜色的 seaborn-xxx 样式将用作样式序列的最后一步,例如,plt.style.use(['seaborn', 'seaborn-poster'])plt.style.use(['seaborn', 'seaborn-muted', 'seaborn-poster'])
  • _ 起始样式也用于修改其他样式,并且
  • 唯一不修改颜色的其他样式fast 就是调整渲染参数以获得更快渲染。

关于python - 从 matplotlib 样式获取颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56211675/

相关文章:

python - 如何在Python中随机指定变量

python - 查找数组是否包含 2 旁边的 2

Python-编写一个for循环来反向显示给定的数字

python - 使用 matplotlib 直接保存到磁盘

python - 为 maptlotlib FuncAnimation 维护一个颜色条

python - 如何在 Jupyter 笔记本中显示之前生成的绘图?

python - 为什么 pyplot.contour() 要求 Z 是二维数组?

python - 为什么索引超出范围的子字符串切片有效?

python - 将多行字符串转换为单行字符串

python - 绘制路径线,给定速度矢量场的条纹线