1、import
import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.patches import ConnectionPatch
2、绘制图形
# 使图表元素中正常显示中文
mpl.rcParams['font.sans-serif'] = 'SimHei'
# 使坐标轴刻度标签正常显示负号
mpl.rcParams['axes.unicode_minus'] = False # 画布
fig = plt.figure(figsize=(12, 6), facecolor='cornsilk' ) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) fig.subplots_adjust(wspace=0) # 定义数据
data = {'category': ['子', '丑', '寅', '卯', '辰'], 'quantity': [138, 181, 118, 107, 387] } others = {'category': ['甲', '乙', '丙'], 'quantity': [98, 170, 119] } # 大饼图
labs = data['category'] quantity = data['quantity'] explode = (0, 0, 0, 0, 0.03) # 分裂距离
ax1.pie(x=quantity, colors=['r', 'g', 'm', 'c', 'y'], explode=explode, autopct='%1.1f%%', startangle=70, labels=labs, textprops={'color': 'k', 'fontsize': 12, } ) # 小饼图
labs2 = others['category'] quantity_2 = others['quantity'] ax2.pie(x=quantity_2, colors=['khaki', 'olive', 'gold'], autopct='%1.1f%%', startangle=70, labels=labs2, radius=0.5, shadow=True, textprops={'color': 'k', 'fontsize': 12, }, ) # 用 ConnectionPatch 画出两个饼图的间连线 ## 饼图边缘的数据
theta1 = ax1.patches[-1].theta1 theta2 = ax1.patches[-1].theta2 center = ax1.patches[-1].center r = ax1.patches[-1].r width=0.2
# 上边缘的连线
x = r*np.cos(np.pi/180*theta2)+center[0] y = np.sin(np.pi/180*theta2)+center[1] con_a = ConnectionPatch(xyA=(-width/2,0.5), xyB=(x,y), coordsA='data', coordsB='data', axesA=ax2, axesB=ax1 ) # 下边缘的连线
x = r*np.cos(np.pi/180*theta1)+center[0] y = np.sin(np.pi/180*theta1)+center[1] con_b = ConnectionPatch(xyA=(-width/2,-0.5), xyB=(x,y), coordsA='data', coordsB='data', axesA=ax2, axesB=ax1 ) for con in [con_a, con_b]: con.set_linewidth(1) # 连线宽度
con.set_color=([0,0,0]) # 连线颜色
ax2.add_artist(con) # 添加连线
图形效果: