[英]How do I draw a line connecting subplots in pyplot?
我想在pyplot中的子圖之間創建線條,如此處的紅色虛線所示(在pdf編輯器中添加)。
我已經閱讀了有關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)
ConnectionPatch示例顯示了如何使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.