我找不到解决方案,所以我自己动手解决了。我使用了matplotlib.patches模块中的ConnectionPatch对象。这允许您在同一图中的不同坐标轴之间绘制线条。以下代码创建了一个左侧为饼图,右侧为堆叠条形图:
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np
import math
plt.style.use('fivethirtyeight')
fig = plt.figure(figsize=(15,7.5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ratios = [.4, .56, .04]
labels = ['Approve', 'Disapprove', 'Undecided']
explode=[0.1,0,0]
angle = -180*ratios[0]
ax1.pie(ratios, autopct='%1.1f%%', startangle=angle,
labels=labels,explode=explode )
xpos = 0
bottom = 0
ratios = [.33, .54, .07, .06]
width = .2
colors = ['y','m','#99ff99','#ffcc99']
for j in range(len(ratios)):
height = ratios[j]
ax2.bar(xpos, height, width, bottom=bottom, color=colors[j])
ypos = bottom + ax2.patches[j].get_height()/2
bottom += height
ax2.text(xpos,ypos, "%d%%" %
(ax2.patches[j].get_height()*100), ha='center')
plt.title('Gender of approvers')
plt.legend(('Women', 'Men', 'Gender Neutral', 'Alien'))
plt.axis('off')
plt.xlim(-2.5*width, 2.5*width)
然后,我添加了两行,分别将饼图的第一个楔形连接到堆积条形图的顶部和底部:
theta1, theta2 = ax1.patches[0].theta1, ax1.patches[0].theta2
center, r = ax1.patches[0].center, ax1.patches[0].r
bar_height = sum([item.get_height() for item in ax2.patches])
x = r*np.cos(math.pi/180*theta2)+center[0]
y = np.sin(math.pi/180*theta2)+center[1]
con = ConnectionPatch(xyA=(-width/2,bar_height), xyB=(x,y),
coordsA="data", coordsB="data", axesA=ax2, axesB=ax1)
con.set_color([0,0,0])
con.set_linewidth(4)
ax2.add_artist(con)
x = r*np.cos(math.pi/180*theta1)+center[0]
y = np.sin(math.pi/180*theta1)+center[1]
con = ConnectionPatch(xyA=(-width/2,0), xyB=(x,y),
coordsA="data", coordsB="data", axesA=ax2, axesB=ax1)
con.set_color([0,0,0])
ax2.add_artist(con)
con.set_linewidth(4)
plt.show()
这是情节概述: