Python 饼状图标签重叠问题

import csv
import matplotlib.pyplot as plt
import numpy as np
import collections
import itertools

plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Microsoft Yahei']

The_Labels = ['none', 'primary', 'junior', 'senior', 'specialties', 'bachelor', 'master']
contract_amounts = [1,0.2,1,4,5,6,8]

#合并,排序
y = zip(The_Labels, contract_amounts)
y = sorted(y, key=lambda x: x[1])
print(y)
#解压数组
newlabel, newnum = zip(*y)

plt.figure(figsize=(8,4))
# 绘制圆环图
colors = plt.get_cmap('Blues')(np.linspace(0.2,1,len(contract_amounts)))

# 绘制圆环图
pieee = plt.pie(newnum, colors=colors, autopct='%1.1f%%', startangle=0, wedgeprops={'width': 0.5, 'edgecolor': 'white'})
for i, p in enumerate(pieee[0]):
    # 计算标签位置
    angle = (p.theta2 - p.theta1) / 2.0 + p.theta1
    labely = np.sin(angle / 180 * np.pi)
    labelx = np.cos(angle / 180 * np.pi)

    # 设置连接方式
    connect = f"angle,angleA=0,angleB={angle}"

    # 设置对齐方式
    align = {-1: "right", 1: "left"}[int(np.sign(labelx))]

    if (np.sign(labelx) > 0):
        plt.annotate(
        newlabel[i],
        xy = (labelx, labely),
        xycoords='data',
        xytext = ((1.3 - i * 0.08)*np.sign(labelx),
                  (1.1 + i * 0.01) * labely),
                  fontsize = 10,
                  horizontalalignment = align,
                  arrowprops=dict(arrowstyle="-",connectionstyle=connect),
                  zorder=0,
                  va="center"
        )
    else:
        plt.annotate(
        newlabel[i],
        xy = (labelx, labely),
        xycoords='data',
        xytext = ((1.8 - i * 0.1)*np.sign(labelx),
                  (1.1 + i * 0.01) * labely),
                  fontsize = 10,
                  horizontalalignment = align,
                  arrowprops=dict(arrowstyle="-",connectionstyle=connect),
                  zorder=0,
                  va="center"
        )

plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值