传说仅适用于熊猫中的两个馅饼之一

我做了两个馅饼:一个在里面。我也想做一个传奇,但只限于内心。 还有一件很重要的事情:内圈只有两个标签,重复了5次,所以当我为两个饼做图例时,我会得到诸如“付费,免费,付费,免费等”的标签

...
titles = ['Free', 'Paid']
subgroup_names= 5*titles
subgroup_size = final.num.tolist()

a, b, c = [plt.cm.Blues, plt.cm.Reds, plt.cm.Greens]
#Outer ring
fig, ax = plt.subplots()
ax.axis('equal')
mypie, _ = ax.pie(group_size, radius = 2.5, labels = group_names,
                  colors = [a(0.7), a(0.6), a(0.5), a(0.4), a(0.3)])
plt.setp(mypie, width = 1, edgecolor = 'white')

#Inner ring
mypie2, _ = ax.pie(subgroup_size, radius = 1.6, labels = subgroup_names,
                   labeldistance = 0.7, colors = [b(0.5), c(0.5)])
plt.setp(mypie2, width = 0.8, edgecolor = 'white')

plt.legend()

plt.show()
评论
  • gest
    gest 回复

    plt.legend accepts a list of handles and labels as parameters. get_legend_handles_labels() conveniently gets a list of handles and of labels that would normally be used. Via list indexing you can grab the interesting part.

    To center the labels inside the plot, the textprops= parameter of plt.pie accepts a horizontal and vertical alignment.

    import matplotlib.pyplot as plt
    import numpy as np
    
    titles = ['Free', 'Paid']
    subgroup_names = 5 * titles
    subgroup_size = np.random.uniform(10, 30, len(subgroup_names))
    group_size = subgroup_size.reshape(5, 2).sum(axis=1)
    group_names = [f'Group {l}' for l in 'abcde']
    
    a, b, c = [plt.cm.Blues, plt.cm.Reds, plt.cm.Greens]
    # Outer ring
    fig, ax = plt.subplots()
    ax.axis('equal')
    mypie, _ = ax.pie(group_size, radius=2.5, labels=group_names,
                      colors=[a(0.7), a(0.6), a(0.5), a(0.4), a(0.3)])
    plt.setp(mypie, width=1, edgecolor='white')
    
    # Inner ring
    mypie2, _ = ax.pie(subgroup_size, radius=1.6, labels=subgroup_names,
                       labeldistance=0.7, colors=[b(0.5), c(0.5)],
                       textprops={'va': 'center', 'ha': 'center'})
    plt.setp(mypie2, width=0.8, edgecolor='white')
    
    handles, labels = plt.gca().get_legend_handles_labels()
    labels_to_skip = len(group_names)
    plt.legend(handles[labels_to_skip:labels_to_skip + 2], labels[labels_to_skip:labels_to_skip + 2])
    plt.show()
    

    demo plot

    PS: To leave out the labels from the pie chart and only have them in the legend, call plt.pie() without the labels= parameter. And create the legend from the patches returned by plt.pie() (limited to the first two in this case):

    # Inner ring
    mypie2, _ = ax.pie(subgroup_size, radius=1.6,
                       labeldistance=0.7, colors=[b(0.5), c(0.5)])
    plt.setp(mypie2, width=0.8, edgecolor='white')
    plt.legend(mypie2[:len(titles)], titles)
    

    labels only in the legend