如何使用 Python 在两个子图中绘制一条虚线?

时间:2021-02-25 00:31:02

标签: python matplotlib subplot

import matplotlib.pyplot as plt
import numpy as np

time = np.linspace(-1,5, 100)

fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True, figsize=(5,5))
ax1.plot([-1,0,0,5], [1,1,0,0], color='navy')
ax1.set_ylim(-0.1,1.2)
ax2.plot(time, np.clip(np.exp(-time),0,1), color='darkolivegreen')
ax2.set_ylim(-0.1,1.2)
ax3.plot(time, np.clip(np.exp(-time),0,0.4), color='darksalmon')
ax3.set_ylim(-0.1,0.8)

我制作了三个子图并将它们垂直排列(x 轴共享)。是否有一种方便的方法可以添加两条穿过所有三个子图的垂直线 x=0x=-log(0.4)

1 个答案:

答案 0 :(得分:0)

您可以使用axvline()

import matplotlib.pyplot as plt
import numpy as np

time = np.linspace(-1.5, 100)

fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True, figsize=(5,5))
ax1.plot([-1,0,0,5], [1,1,0,0], color='navy')
ax1.set_ylim(-0.1,1.2)
ax2.plot(time, np.clip(np.exp(-time),0,1), color='darkolivegreen')
ax2.set_ylim(-0.1,1.2)
ax3.plot(time, np.clip(np.exp(-time),0,0.4), color='darksalmon')
ax3.set_ylim(-0.1,0.8)

# add vertical lines to all subplots
for ax in [ax1, ax2, ax3]:
    ax.axvline(20, c='r')

这给出:

plot with vertical lines

如果你想让垂直线穿过整个图形,你需要设置一个额外的子图,与三个子图加在一起一样大,并使其背景透明。然后你可以在背景子图中画线:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

time = np.linspace(-1.5, 100)

fig = plt.figure()
gs = fig.add_gridspec(3, 2)


ax1 = fig.add_subplot(gs[0, :])
ax1.plot([-1,0,0,5], [1,1,0,0], color='navy')
ax1.set_ylim(-0.1,1.2)

ax2 = fig.add_subplot(gs[1, :], sharex = ax1)
ax2.plot(time, np.clip(np.exp(-time),0,1), color='darkolivegreen')
ax2.set_ylim(-0.1,1.2)

ax3 = fig.add_subplot(gs[2, :], sharex = ax1)
ax3.plot(time, np.clip(np.exp(-time),0,0.4), color='darksalmon')
ax3.set_ylim(-0.1,0.8)

# background axes object for plotting the vertical line
ax =  fig.add_subplot(gs[:, :], sharex = ax1)
# set background color to transparent and turn off the frame
ax.patch.set_alpha(0)
ax.axis("off")
# plot the vertical line
ax.axvline(20, c='r')

plt.show()

这给出:

plot long vertical line

相关问题