为 Matplotlib 饼图中的数据分配特定颜色

Cha*_*ron 10 python charts matplotlib python-2.7 pie-chart

我正在尝试创建饼图matplotlib,其中每个类别的颜色都是固定的。

我有一个函数可以根据值和类别数据集创建饼图。下面是一个例子:

Category     Value
TI           65
Con          43
FR           40
TraI         40
Bug          38
Data         22
Int          15
KB           12
Other        8
Dep          7
PW           6
Uns          5
Perf         4
Dep          3
Run Code Online (Sandbox Code Playgroud)

问题是数据从一个实例到另一个实例不同,这反过来又改变了类别的顺序。因此,每次我生成图表时,每个类别都会被标记为不同的颜色。我每次都可以按字母顺序对数据进行排序,但这会导致两个问题:某些数据集中缺少某些类别,而且我更喜欢按大小排序,以便最小的楔子水平定向。

如何matplotlib根据 a 的索引设置分配颜色pandas.Series

这是我用来生成饼图的代码:

import matplotlib.pyplot as plt

slices = [62, 39, 39, 38, 37, 21, 15,  9,  6,  7,  6,  5,  4, 3]

cmap = plt.cm.prism
colors = cmap(np.linspace(0., 1., len(slices)))

labels = [u'TI', u'Con', u'FR', u'TraI', u'Bug', u'Data', u'Int', u'KB', u'Other', u'Dep', u'PW', u'Uns', u'Perf', u'Dep']

fig = plt.figure(figsize=[10, 10])
ax = fig.add_subplot(111)

pie_wedge_collection = ax.pie(slices, colors=colors, labels=labels, labeldistance=1.05, autopct=make_autopct(slices))

for pie_wedge in pie_wedge_collection[0]:
    pie_wedge.set_edgecolor('white')

titlestring = 'Issues'

ax.set_title(titlestring)
Run Code Online (Sandbox Code Playgroud)

编辑:我忘了解释这个autopct函数,它用于添加值和百分比标签:

def make_autopct(values):
    def my_autopct(pct):
        total = sum(values)
        val = int(round(pct*total/100.0))
        return '{p:.2f}%  ({v:d})'.format(p=pct,v=val)
    return my_autopct
Run Code Online (Sandbox Code Playgroud)

tmd*_*son 8

这是您可以尝试的想法。根据您的标签和颜色制作字典,以便将每种颜色映射到一个标签。然后,在制作饼图后,facecolor使用此字典分配楔形。

这是一段未经测试的代码,可能会满足您的要求:

import numpy as np
import matplotlib.pyplot as plt

def mypie(slices,labels,colors):

    colordict={}
    for l,c in zip(labels,colors):
        print l,c
        colordict[l]=c

    fig = plt.figure(figsize=[10, 10])
    ax = fig.add_subplot(111)

    pie_wedge_collection = ax.pie(slices, labels=labels, labeldistance=1.05)#, autopct=make_autopct(slices))

    for pie_wedge in pie_wedge_collection[0]:
        pie_wedge.set_edgecolor('white')
        pie_wedge.set_facecolor(colordict[pie_wedge.get_label()])

    titlestring = 'Issues'

    ax.set_title(titlestring)

    return fig,ax,pie_wedge_collection

slices = [37, 39, 39, 38, 62, 21, 15,  9,  6,  7,  6,  5,  4, 3]
cmap = plt.cm.prism
colors = cmap(np.linspace(0., 1., len(slices)))
labels = [u'TI', u'Con', u'FR', u'TraI', u'Bug', u'Data', u'Int', u'KB', u'Other', u'Dep', u'PW', u'Uns', u'Perf', u'Dep']

fig,ax,pie_wedge_collection = mypie(slices,labels,colors)

plt.show()
Run Code Online (Sandbox Code Playgroud)

  • 没有更简单的方法吗?? (3认同)

Ral*_*lph 6

这是@tmdavison 答案的更简单的解决方案。

让我们先看看 MWE 的问题:

import matplotlib.pyplot as plt

labels = ['Frogs', 'Hogs', 'Dogs', 'Logs']
sizes = [15, 30, 45, 10]

fig, ax = plt.subplots(1, 2)

ax[0].pie(sizes, labels=labels)
ax[1].pie(sizes[1:], labels=labels[1:])
Run Code Online (Sandbox Code Playgroud)

这会产生问题图:

在此处输入图片说明

问题是,在左手的情节,Hogs是橙色,但在右边图Hogs中为蓝色(具有类似混淆的LogsDogs)。

我们希望两个图中的标签颜色相同。我们可以通过指定要使用的颜色字典来做到这一点:

import matplotlib.pyplot as plt

labels = ['Frogs', 'Hogs', 'Dogs', 'Logs']
sizes = [15, 30, 45, 10]

fig, ax = plt.subplots(1, 2)

ax[0].pie(sizes, labels=labels)
ax[1].pie(sizes[1:], labels=labels[1:])
Run Code Online (Sandbox Code Playgroud)

这适用于创建情节:

在此处输入图片说明

在这里,我们看到标签根据需要在两个图中用相同的颜色表示。

如果您有很多类别,为每个类别手动设置颜色可能会很麻烦。在这种情况下,您可以将colours字典构造为:

colours = dict(zip(labels, plt.cm.tab10.colors[:len(labels)]))
Run Code Online (Sandbox Code Playgroud)

如果您有 10 个以上的类别,您可以使用:

colours = dict(zip(labels, plt.cm.tab20.colors[:len(labels)]))
Run Code Online (Sandbox Code Playgroud)