实际上,我发现了另一个与我想要的东西非常相似的主题:
Use subplots to zoom into timeseries or how I can draw lines outside of axis borders
所以这里的代码:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
def zoomingBox(ax1, roi, ax2, color='red', linewidth=2):
ax1.add_patch(Rectangle([roi[0],roi[2]], roi[1]-roi[0], roi[3]-roi[2],**dict([('fill',False), ('linestyle','dashed'), ('color',color), ('linewidth',linewidth)]) ))
srcCorners = [[roi[0],roi[2]], [roi[0],roi[3]], [roi[1],roi[2]], [roi[1],roi[3]]]
dstCorners = ax2.get_position().corners()
srcBB = ax1.get_position()
dstBB = ax2.get_position()
if (dstBB.min[0]>srcBB.max[0] and dstBB.max[1]srcBB.max[1]):
src = [0, 3]; dst = [0, 3]
elif (dstBB.max[0]srcBB.max[0] and dstBB.min[1]>srcBB.max[1]):
src = [1, 2]; dst = [1, 2]
elif dstBB.max[1] < srcBB.min[1]:
src = [0, 2]; dst = [1, 3]
elif dstBB.min[1] > srcBB.max[1]:
src = [1, 3]; dst = [0, 2]
elif dstBB.max[0] < srcBB.min[0]:
src = [0, 1]; dst = [2, 3]
elif dstBB.min[0] > srcBB.max[0]:
src = [2, 3]; dst = [0, 1]
for k in range(2):
ax1.annotate('', xy=dstCorners[dst[k]], xytext=srcCorners[src[k]], xycoords='figure fraction', textcoords='data', arrowprops=dict([('arrowstyle','-'), ('color',color), ('linewidth',linewidth)]))
t=np.arange(1000)
x=np.sin(np.arange(1000)/10)
plt.figure()
ax1 = plt.subplot(2,1,1)
plt.plot(t,x)
ax2 = plt.subplot(2,2,3)
plt.plot(t[100:200],x[100:200])
ax3 = plt.subplot(2,2,4)
plt.plot(t[600:700],x[600:700])
zoomingBox(ax1, [100,200,-1.1,1.1], ax2)
zoomingBox(ax1, [600,700,-1.1,1.1], ax3)
plt.show()
这给出了: