Assign specific colours to data in Matplotlib pie chart

后端 未结 2 1422
野的像风
野的像风 2021-01-18 07:10

I\'m trying to create pie charts with matplotlib in which the colour of each category is fixed.

I\'ve got a function which creates a pie chart from sets

2条回答
  •  独厮守ぢ
    2021-01-18 07:47

    Here's an idea you could try. Make a dictionary from your labels and colors, so each color is mapped to a label. Then, after making the pie chart, go in an assign the facecolor of the wedge using this dictionary.

    Here's an untested bit of code which might do what you are looking for:

    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()
    

提交回复
热议问题