Reputation: 99
I am trying to create a figure consisting of multiple subplots stacked on top of each other. However, I also want a single plot that runs through all the stacked subplots and shows up "behind" them. I'm not concerned about the actual y-values so it's fine that the y-axis is unreadable in this case. Below is what I have so far:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 100)
y = x
y2 = x**2
y3 = x**3
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.4])
ax2 = fig.add_axes([0.1, 0.5, 0.8, 0.4])
ax3 = ax1.twinx()
ax4 = ax2.twinx()
ax1.plot(x, y)
ax2.plot(x, y3)
ax3.plot(x, y2)
ax4.plot(x, y2)
Essentially, I want ax3 and ax4 to combine into one large plot that shows a single quadratic function while having a cubic function stacked on top of a linear function in the same figure. Ideally, I'll have three actually separate axes since I'll want to be customizing and performing actions to one subplot without affecting the other two in the future.
Thanks!
Upvotes: 0
Views: 206
Reputation: 339150
I guess the idea would be to first create two subplots one below the other and reduce the spacing in between to 0. Then create a new subplot covering the complete area and make the background transparent. Also put the ticks and labels of the third axes to the right. Then plot to each of the three axes.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 100)
y = x
y2 = x**2
y3 = x**3
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
fig.subplots_adjust(hspace=0.0)
ax3 = fig.add_subplot(111, sharex=ax1, label="right axes")
l1, = ax1.plot(x, y, color="C0")
l2, = ax2.plot(x, y3, color="C2")
l3, = ax3.plot(x, y2, color="C3")
ax1.tick_params(axis="y", colors=l1.get_color())
ax2.tick_params(axis="y", colors=l2.get_color())
ax3.set_facecolor("none")
ax3.tick_params(labelbottom=False, bottom=False, labelleft=False, left=False,
right=True, labelright=True, colors=l3.get_color())
plt.show()
Upvotes: 2