【问题标题】:Overlapping labels in matplotlib pie chartmatplotlib 饼图中的重叠标签
【发布时间】:2020-04-08 13:37:15
【问题描述】:

我想构建一个饼图,但是我的标签一直重叠(我有一个大楔形和十个小楔形)。经过一些研究,我发现了similar question 的答案,但是它对我不起作用,这是输出:

有没有办法可靠地注释我的饼图,使标签不会重叠或部分交叉进入饼图本身?

这是我的代码:

import matplotlib.pyplot as plt
import math

labels = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven"]
fig, ax = plt.subplots()
values = [574.51,
 272.3333,
 250.0,
 221.0,
 164.0,
 135.0,
 114.10000000000001,
 112.31708,
 100.0,
 91.8,
 2209.0827639999993]

l = ax.pie(values, startangle=-90)

for label, t in zip(labels, l[1]):
    x, y = t.get_position()
    angle = int(math.degrees(math.atan2(y, x)))
    ha = "left"
    va = "bottom"

    if angle > 90:
        angle -= 180

    if angle < 0:
        va = "top"

    if -45 <= angle <= 0:
        ha = "right"
        va = "bottom"

    plt.annotate(label, xy=(x,y), rotation=angle, ha=ha, va=va, size=8)

【问题讨论】:

  • 只删除ha = 'right这行?因为它奇怪地移动了你的“三”和“二”标签。
  • 也将我的“十一”标签推到了里面
  • 我还有几个饼图,标签到处都是。我没有找到一种可靠的方法来用这种向外的样式标记图表
  • 对于“十一”,您可以将 ha = 'right' 添加到 if angle &gt; 90: 案例中。这玩弄angle 是相当奇怪的。 Atan2 给出 -180 到 180 之间的角度。因此,将 ha = 'left' 设置为 -90 到 90 之间的角度,否则设置 ha = 'right' 似乎就足够了?

标签: matplotlib


【解决方案1】:

做一些改变会有所帮助(它最终会比你所拥有的更容易):1)使用x来决定它是在图表的左边还是右边,这不是必需的,但它是比角度更容易混淆; 2)使用rotation_mode = "anchor",所以对齐发生在旋转之前; 3) 使用va = "center" 旋转。

这就是我的输出结果(我更改了数据值,以便演示所有象限中的对齐方式)。

还有代码:

labels = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven"]
fig, ax = plt.subplots()
values = [574.51,
 272.3333,
 1050.0,
 221.0,
 164.0,
 935.0,
 114.10000000000001,
 112.31708,
 100.0,
 91.8,
 2209.0827639999993]

l = ax.pie(values, startangle=-90)

for label, t in zip(labels, l[1]):
    x, y = t.get_position()
    angle = int(math.degrees(math.atan2(y, x)))
    ha = "left"

    if x<0:
        angle -= 180
        ha = "right"

    plt.annotate(label, xy=(x,y), rotation=angle, ha=ha, va="center", rotation_mode="anchor", size=8)

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多