在 Matplotlib 饼图中有条件地去除标签 [英] Conditional removal of labels in Matplotlib pie chart

查看:140
本文介绍了在 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()

产生以下内容:

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

My question is, how can I remove the label based on a condition. For example I'd only want to display labels with percent > 20%. Such that the labels and value of a,c,d won't be displayed in X, etc.

推荐答案

pie 可以是可调用的,它将接收当前百分比.因此,您只需要提供一个函数,该函数为要省略百分比的值返回一个空字符串.

The autopct argument from pie can be a callable, which will receive the current percentage. So you only would need to provide a function that returns an empty string for the values you want to omit the percentage.

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

ax.pie(df[col], labels=df.index, autopct=my_autopct, colors=colors)

如果您需要对 autopct 参数上的值进行参数化,您将需要一个返回函数的函数,例如:

If you need to parametrize the value on the autopct argument, you'll need a function that returns a function, like:

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)

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

For the labels, the best thing I can come up with is using list comprehension:

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)

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

Note, however, that the legend by default is being generated from the first passed labels, so you'll need to pass all values explicitly to keep it intact.

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

这篇关于在 Matplotlib 饼图中有条件地去除标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆