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) # 添加連線
圖形效果: