Assign specific colours to data in Matplotlib pie chart

后端 未结 2 1406
野的像风
野的像风 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:52

    Here is a simpler solution to @tmdavison's answer.

    Let's first see the problem with an 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:])
    

    This produces the problem plots:

    The problem is that in the left-hand plot, Hogs is coloured in orange, but in the right-hand plot Hogs is coloured in blue (with a similar mix-up for Logs and Dogs).

    We would like the colours for the labels to be the same across both plots. We can do this by specifying a dictionary of colours to use:

    labels = ['Frogs', 'Hogs', 'Dogs', 'Logs']
    sizes = [15, 30, 45, 10]
    colours = {'Frogs': 'C0',
               'Hogs': 'C1',
               'Dogs': 'C2',
               'Logs': 'C3'}
    
    fig, ax = plt.subplots(1, 2)
    
    ax[0].pie(sizes,
              labels=labels,
              colors=[colours[key] for key in labels])
    
    ax[1].pie(sizes[1:],
              labels=labels[1:],
              colors=[colours[key] for key in labels[1:]])
    

    This works to create the plot:

    Here we see that the labels are represented by the same colours across both plots, as desired.

    If you have lots of categories it can be cumbersome to manually set a colour for each category. In this case you could construct the colours dictionary as:

    colours = dict(zip(labels, plt.cm.tab10.colors[:len(labels)]))
    

    If you have more than 10 categories you would instead use:

    colours = dict(zip(labels, plt.cm.tab20.colors[:len(labels)]))
    

提交回复
热议问题