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()
Python 饼状图标签重叠问题
于 2024-03-01 09:57:39 首次发布