【问题标题】:Pie chart labels are overlapping for same values.对于相同的值,饼图标签重叠。
【发布时间】:2014-04-15 22:27:02
【问题描述】:

这里我正在尝试使用 ma​​tplotlib python 库创建一个饼图。但是,如果值多次相同“0.0”,则日期会重叠。
我的问题是如何单独显示它们。

谢谢。

这是我尝试过的:

from pylab import *

labels = [ "05-02-2014", "23-02-2014","07-02-2014","08-02-2014"]
values = [0, 0, 2, 10]
fig = plt.figure(figsize=(9.0, 6.10)) 
plt.pie(values, labels=labels, autopct='%1.1f%%', shadow=True)
plt.axis('equal')
show()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以手动调整标签位置,尽管这样一个简单的请求需要更多的代码。您可以通过检查放置重复标签的位置来检测重复标签组。

    这是一个示例,其中一些随机数据复制了重叠标签的出现:

    import matplotlib.pyplot as plt
    import numpy as np
    from collections import Counter
    import datetime
    
    # number slices of pie
    num = 10
    
    # generate some labels
    dates = [datetime.datetime(2014,1,1) + datetime.timedelta(days=np.random.randint(1,20)) for i in range(num)]
    labels = [d.strftime('%d-%m-%Y') for d in dates]
    
    # generate some values
    values = np.random.randint(2,10, num)
    
    # force half of them to be zero
    mask = np.random.choice(num, num // 2, replace=False)
    values[mask] = 0
    
    # pick some colors
    colors = plt.cm.Blues(np.linspace(0,1,num))
    
    fig, ax = plt.subplots(figsize=(9.0, 6.10), subplot_kw={'aspect': 1})
    wedges, labels, pcts = ax.pie(values, colors=colors, labels=labels, autopct='%1.1f%%')
    
    
    # find duplicate labels and the amount of duplicates
    c = Counter([l.get_position() for l in labels])
    dups = {key: val for key, val in c.items() if val > 1}
    
    # degrees of spacing between duplicate labels
    offset = np.deg2rad(3.)
    
    
    # loop over any duplicate 'position'
    for pos, n in dups.items():
    
        # select all labels with that position
        dup_labels = [l for l in labels if l.get_position() == pos]
    
        # calculate the angle with respect to the center of the pie
        theta = np.arctan2(pos[1], pos[0])
    
        # get the offsets
        offsets = np.linspace(-(n-1) * offset, (n-1) * offset, n)
    
        # loop over the duplicate labels
        for l, off in zip(dup_labels, offsets):
    
            lbl_radius = 1.3
    
            # calculate the new label positions
            newx = lbl_radius * np.cos(theta + off)
            newy = lbl_radius * np.sin(theta + off)
    
            l.set_position((newx, newy))
    
            # rotate the label
            rot = np.rad2deg(theta + off)
    
            # adjust the rotation so its
            # never upside-down
            if rot > 90:
                rot += 180
            elif rot < -90:
                rot += 180
    
            # rotate and highlight the adjusted labels
            l.set_rotation(rot)
            l.set_ha('center')
            l.set_color('#aa0000')
    

    我特意只修改了重叠的标签以突出效果,但您可以以类似的方式更改所有标签以创建统一的样式。旋转使自动间隔它们变得更容易,但您可以尝试其他放置方式。

    请注意,它只检测真正相等的展示位置,如果您有 [0, 0.00001, 2, 10] 的值,它们可能仍会重叠。

    【讨论】:

    • 谢谢,很有帮助。
    【解决方案2】:

    我不确定是否有办法为每个元素调整“标签距离”,但我可以使用一种棘手的方法来解决这个问题。

    我添加了explode(0, 0.1, 0, 0)

    from pylab import *
    
    labels = [ "05-02-2014", "23-02-2014","07-02-2014","08-02-2014"]
    values = [0, 0, 2, 10]
    explode = (0, 0.1, 0, 0)
    fig = plt.figure(figsize=(9.0, 6.10)) 
    test=range(len(values))
    patches,texts= plt.pie(values, explode=explode,labels=labels,  startangle=90,  radius=0.5 )#pctdistance=1.1,startangle=10, labeldistance=0.8,radius=0.5)
    
    
    
    #plt.axis('equal')
    plt.axis('equal')
    plt.show()
    

    更新 这对我有用,你应该更新 pylab

    【讨论】:

    • @ user3378649 我收到了这个错误——TypeError: pie() got an unexpected keyword argument 'startangle'
    • 现在显示这个 - pie() 得到了一个意外的关键字参数“半径”
    • 您使用的是哪个版本?
    • 我用的是'1.3.1',为了了解你的:>>> import matplotlib >>> matplotlib.__version__
    • explode - 仍然与初始值(日期)重叠。
    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多