如何绘制连接pyplot中子图的线?

时间:2018-11-11 03:29:48

标签: python python-3.x matplotlib

我想在pyplot中的子图之间创建线条,如此处的红色虚线所示(在pdf编辑器中添加)。

enter image description here

我已经阅读了有关connectionpatch的文档,但是我很难充分理解这些示例以翻译成我的特殊情况。就我的情况而言,我包含了代码的简化版本,在相关情况下使用相同的轴结构。如何在子图之间创建这些虚线?

import numpy as np
import matplotlib.pyplot as plt

# Create a 2 x 2 grid: (row, column) 
fig, ax = plt.subplots(2,2) 

# Create a subplot to share common x and y labels
fig.add_subplot(111, frameon=False)
plt.tick_params(
top='off', 
bottom='off', 
left='off', 
right='off')
plt.grid(False)
plt.xlabel('x')
plt.ylabel('function(x)')

# x-axis
x = np.linspace(0,2*np.pi,100)

# Top left
ax[0,0].tick_params(
axis='both',       
which='both',     
bottom=False,      
left=False,
top=False,         
right=False,
labelbottom=False, 
labelleft=False,)
ax[0,0].plot(x,np.sin(x),color='grey')

# Top Right
ax[0,1].tick_params(
axis='both',       
which='both',      
bottom=False,   
left=False,
top=False,        
right=False,
labelbottom=False, 
labelleft=False,)
ax[0,1].plot(x,np.sin(2*x),color='grey')


# Bottom Left
ax[1,0].tick_params(
axis='both',       
which='both',      
bottom=False,      
left=False,
top=False,         
right=False,
labelbottom=False, 
labelleft=False,)
ax[1,0].plot(x,np.cos(x), color='black')

# Bottom Right
ax[1,1].tick_params(
axis='both',      
which='both',     
bottom=False,      
left=False,
top=False,         
right=False,
labelbottom=False, 
labelleft=False,)
ax[1,1].plot(x,np.cos(2*x), color='black')

plt.tight_layout(h_pad=2.5)

1 个答案:

答案 0 :(得分:2)

ConnectionPatch example显示了如何使用ConnectionPatch连接两个轴。对于您的情况,您可以这样做:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch

fig, axes = plt.subplots(2,2) 

# Create a subplot to share common x and y labels
frameax = fig.add_subplot(111, frameon=False)
frameax.grid(False)
frameax.set_xlabel('x', labelpad=10)
frameax.set_ylabel('function(x)',labelpad=10)

for ax in list(axes.flat) + [frameax]:
    ax.tick_params(axis='both', which='both', 
                   bottom=False, left=False, top=False, right=False,
                   labelbottom=False, labelleft=False)

# x-axis
x = np.linspace(0,2*np.pi,100)

axes[0,0].plot(x,np.sin(x),color='grey')
axes[0,1].plot(x,np.sin(2*x),color='grey')
axes[1,0].plot(x,np.cos(x), color='black')
axes[1,1].plot(x,np.cos(2*x), color='black')

kw = dict(linestyle="--", color="red")
cp1 = ConnectionPatch((.5, 0), (.5, 1), "axes fraction", "axes fraction",
                      axesA=axes[0,0], axesB=axes[1,0], **kw)
cp2 = ConnectionPatch((.5, 0), (.5, 1), "axes fraction", "axes fraction",
                      axesA=axes[0,1], axesB=axes[1,1], **kw)

for cp in (cp1, cp2):
    axes[1,1].add_artist(cp)

plt.show()

enter image description here