【问题标题】:Conditionally moving the position of a single data label in a pie chart有条件地移动饼图中单个数据标签的位置
【发布时间】:2020-02-14 23:50:49
【问题描述】:

以下示例代码将生成我将用作示例的圆环图:

import matplotlib.pyplot as plt
%matplotlib inline

# Following should supposedly set the font correctly:
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Muli'] + plt.rcParams['font.sans-serif']
plt.rcParams['font.weight'] = 'extra bold'

size_of_groups=[12,11,30,0.3]

colors = ['#a1daaa','#bbbbb4','#444511','#1afff2']

import matplotlib as mpl
mpl.rcParams['text.color'] = '#273859'

# Create a pieplot
my_pie,texts,_ = plt.pie(size_of_groups,radius = 1.2,colors=colors,autopct="%.1f%%",
textprops = {'color':'w',                                                                                           
             'size':15  #, 'weight':"extra bold"
            }, pctdistance=0.75, labeldistance=0.7) #pctdistance and labeldistance change label positions.
labels=['High','Low','Normal','NA']
plt.legend(my_pie,labels,loc='lower center',ncol=2,bbox_to_anchor=(0.5, -0.2))
plt.setp(my_pie, width=0.6, edgecolor='white') 
fig1 = plt.gcf()
fig1.show()

上面的输出是这样的:

大多数情况下,这很棒。最后我得到了一个漂亮的甜甜圈图!

但最后一件事需要巧妙处理 - 当圆环图的部分非常小(如 0.6%)时,我需要将标签移出图表,并可能改为黑色。

我设法使用 plt.text 为条形图做类似的事情,但我认为饼图根本不可行。我认为以前肯定有人解决过类似的问题,但我不能轻易提出任何体面的解决方案。

【问题讨论】:

  • This post 提出了一些替代方案来解决这个问题。

标签: python matplotlib


【解决方案1】:

这是一种移动小于某个给定数量(代码示例中为 5 度)的补丁的所有百分比文本的方法。请注意,当多个小块彼此靠近时,这也会失败。

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

size_of_groups = [12, 11, 30, 0.3]
colors = ['#a1daaa', '#bbbbb4', '#444511', '#1afff2']
my_pie, texts, pct_txts = plt.pie(size_of_groups, radius=1.2, colors=colors, autopct="%.1f%%",
                                  textprops={'color': 'w', 'size': 15}, pctdistance=0.75,
                                  labeldistance=0.7)
labels = ['High', 'Low', 'Normal', 'NA']
plt.legend(my_pie, labels, loc='lower center', ncol=2, bbox_to_anchor=(0.5, -0.2))
plt.setp(my_pie, width=0.6, edgecolor='white')

for patch, txt in zip(my_pie, pct_txts):
    if (patch.theta2 - patch.theta1) <= 5:
        # the angle at which the text is normally located
        angle = (patch.theta2 + patch.theta1) / 2.
        # new distance to the pie center
        x = patch.r * 1.2 * np.cos(angle * np.pi / 180)
        y = patch.r * 1.2 * np.sin(angle * np.pi / 180)
        # move text to new position
        txt.set_position((x, y))
        txt.set_color('black')
plt.tight_layout()
plt.show()

【讨论】:

  • 再一次,我坐在这里,下巴掉了下来,想知道“他怎么会知道这一点”。非常感谢。
【解决方案2】:

我尝试通过调整ImportanceOfBeingErnest 的解决方案来解决给定here 的不同问题。由于某种原因,我的系统中没有显示百分号,但您可以弄清楚

rad = 1.2 # Define a radius variable for later use

my_pie, texts, autotexts = plt.pie(size_of_groups, radius=rad, colors=colors, autopct="%.1f%%",
                     pctdistance=0.75, labeldistance=0.7, textprops={'color':'white', 'size':20}) 

# Rest of the code

cx, cy = 0, 0 # Center of the pie chart 

for t in autotexts:
    x, y = t.get_position()
    text = t.get_text()

    if float(text.strip('%')) < 1: # Here 1 is the target threshold percentage
        angle = np.arctan2(y-cy, x-cx)
        xt, yt = 1.1*rad*np.cos(angle)+cx, 1.1*rad*np.sin(angle)+cy
        t.set_color("k")
        t.set_position((xt,yt))      

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    相关资源
    最近更新 更多