有条件地删除Matplotlib饼图中的标签

nev*_*int 6 python matplotlib

我有以下代码:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], 
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=3)
for ax in axes.flat:
    ax.axis('off')

for ax, col in zip(axes.flat, df.columns):
    ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

axes[0, 0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()
Run Code Online (Sandbox Code Playgroud)

产生以下内容:

在此输入图像描述

我的问题是,如何根据条件删除标签.例如,我只想显示百分比> 20%的标签.这样标签和价值a,c,d不会在X等中显示

mem*_*lyk 13

autopct从参数pie可以是调用,将接收的电流百分比.所以你只需要提供一个函数,为你想要省略百分比的值返回一个空字符串.

def my_autopct(pct):
    return ('%.2f' % pct) if pct > 20 else ''

ax.pie(df[col], labels=df.index, autopct=my_autopct, colors=colors)
Run Code Online (Sandbox Code Playgroud)

如果需要参数化参数的值,则autopct需要一个返回函数的函数,如:

def autopct_generator(limit):
    def inner_autopct(pct):
        return ('%.2f' % pct) if pct > limit else ''
    return inner_autopct

ax.pie(df[col], labels=df.index, autopct=autopct_generator(20), colors=colors)
Run Code Online (Sandbox Code Playgroud)

对于标签,我能想到的最好的事情是使用列表理解:

for ax, col in zip(axes.flat, df.columns):                                                             
    data = df[col]                                                                                     
    labels = [n if v > data.sum() * 0.2 else ''
              for n, v in zip(df.index, data)]                       

    ax.pie(data, autopct=my_autopct, colors=colors, labels=labels)
Run Code Online (Sandbox Code Playgroud)

但请注意,默认情况下,图例是从第一个传递的标签生成的,因此您需要显式传递所有值以保持其完整.

axes[0, 0].legend(df.index, bbox_to_anchor=(0, 0.5))
Run Code Online (Sandbox Code Playgroud)