make matplotlib fill_between 覆盖前面的子图
make matplotlib fill_between overwrite the subplot in front
我正在尝试绘制几条部分重叠并相互遮挡的线。这是我试过的:
# Create the figure
fig = plt.figure(figsize=(7, 4))
ax = plt.subplot(111)
# remove grid
ax.set_xticks([])
ax.set_yticks([])
# define data
X = np.linspace(-2*np.pi, 2*np.pi, 400)
Y1 = np.cos(2*X)
Y2 = X**2/10-0.5
ax.plot(X, Y1, lw=1)
ax.fill_between(X, Y1, -1, facecolor=(1,0,0,1))
ax.plot(X, Y2)
ax.fill_between(X, Y2, -1, facecolor=(1,1,1,1))
plt.show()
产生
但是当第二个 fill_between
下降到 -1 时,我希望它也遮挡蓝色图形。像这样:
如有任何建议,我们将不胜感激。
我的解决方案:
# Create the figure
fig = plt.figure(figsize=(7, 4))
ax = plt.subplot(111)
# remove grid
ax.set_xticks([])
ax.set_yticks([])
# define data
X = np.linspace(-2*np.pi, 2*np.pi, 400)
Y1 = np.cos(2*X)
Y2 = X**2/10-0.5
# NEW #########################
for i in range(Y1.size):
if Y1[i] < Y2[i] :
Y1[i] = Y2[i]
###############################
ax.plot(X, Y1, lw=1, color="blue")
ax.fill_between(X, Y1, -1, facecolor=(1,0,0,1))
ax.plot(X, Y2, color="orange")
ax.fill_between(X, Y2, -1, facecolor=(1,1,1,1))
plt.show()
输出:
基本上在 Y1 小于 Y2 的任何点,我们将 Y1 上的点设置为等于 Y2。
我最终采纳了@JohanC 的建议,因为它可以更容易地推广到更多图表。例如
ax.plot(X, Y1, lw=1)
ax.fill_between(X, Y1, -1, facecolor=(1,0,0,1), zorder=2)
ax.plot(X, Y2)
ax.fill_between(X, Y2, -1, facecolor=(1,1,1,1), zorder=3)
ax.plot(X, Y3, lw=1, zorder=1)
ax.fill_between(X, Y3, -1, facecolor=(0,0,1,1), zorder=1)
ax.plot(X, Y4, lw=1, zorder=0)
ax.fill_between(X, Y4, -1, facecolor=(0,1,0,0.5), zorder=0)
可以这样画:
我正在尝试绘制几条部分重叠并相互遮挡的线。这是我试过的:
# Create the figure
fig = plt.figure(figsize=(7, 4))
ax = plt.subplot(111)
# remove grid
ax.set_xticks([])
ax.set_yticks([])
# define data
X = np.linspace(-2*np.pi, 2*np.pi, 400)
Y1 = np.cos(2*X)
Y2 = X**2/10-0.5
ax.plot(X, Y1, lw=1)
ax.fill_between(X, Y1, -1, facecolor=(1,0,0,1))
ax.plot(X, Y2)
ax.fill_between(X, Y2, -1, facecolor=(1,1,1,1))
plt.show()
产生
但是当第二个 fill_between
下降到 -1 时,我希望它也遮挡蓝色图形。像这样:
如有任何建议,我们将不胜感激。
我的解决方案:
# Create the figure
fig = plt.figure(figsize=(7, 4))
ax = plt.subplot(111)
# remove grid
ax.set_xticks([])
ax.set_yticks([])
# define data
X = np.linspace(-2*np.pi, 2*np.pi, 400)
Y1 = np.cos(2*X)
Y2 = X**2/10-0.5
# NEW #########################
for i in range(Y1.size):
if Y1[i] < Y2[i] :
Y1[i] = Y2[i]
###############################
ax.plot(X, Y1, lw=1, color="blue")
ax.fill_between(X, Y1, -1, facecolor=(1,0,0,1))
ax.plot(X, Y2, color="orange")
ax.fill_between(X, Y2, -1, facecolor=(1,1,1,1))
plt.show()
输出:
基本上在 Y1 小于 Y2 的任何点,我们将 Y1 上的点设置为等于 Y2。
我最终采纳了@JohanC 的建议,因为它可以更容易地推广到更多图表。例如
ax.plot(X, Y1, lw=1)
ax.fill_between(X, Y1, -1, facecolor=(1,0,0,1), zorder=2)
ax.plot(X, Y2)
ax.fill_between(X, Y2, -1, facecolor=(1,1,1,1), zorder=3)
ax.plot(X, Y3, lw=1, zorder=1)
ax.fill_between(X, Y3, -1, facecolor=(0,0,1,1), zorder=1)
ax.plot(X, Y4, lw=1, zorder=0)
ax.fill_between(X, Y4, -1, facecolor=(0,1,0,0.5), zorder=0)
可以这样画: