61

I have a two-by-two plot that I am creating dynamically. In the first row I want to plot density functions, in the second row CDFs. I want

  • each of the columns to share x
  • each of the rows to share y

That is, two objects aligned vertically have the same x-axis, and two plots aligned horizontally have the same y-axis.

However, sharex and sharey force them to be the same for all of the subplots. How can I fix this sort of axes sharing? I understand that I could be manually giving each axes a share partner, but that wouldn't work with the generic structure that follows:

fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True)
for i, lam in enumerate(lams):
    axesNow = [axs[i] for axs in axes]  # pick the ith column from axes
    for i, Param.p in enumerate(pp):
        axesNow[0].plot(somethingWithPDF)
        axesNow[1].plot(somethingWithCDF)

for ax in axes.flatten(): ax.legend()

enter image description here

2 Answers 2

149

The pyplot.subplots documentation describes the 'col' and 'row' options for the sharex and sharey kwargs. In particular, I think you want:

fig, axes = plt.subplots(nrows=2, ncols=2, sharex='col', sharey='row')
0
0

What about something like this, where all axes are built individually:

x1 = np.arange(5)
y1 = np.arange(3, 8)
ax1 = plt.subplot(223)
ax1.plot(x1, y1)
ax1.set_title("ax1")

x2 = np.arange(5, 10)
y2 = np.arange(3, 8)
ax2 = plt.subplot(224, sharey=ax1)
ax2.plot(x2, y2)
ax2.set_title("ax2")
#plt.setp(ax2.get_yticklabels(), visible=False) # Use this to hide axes labels


x3 = x1
y3 = np.arange(13, 8, -1)
ax3 = plt.subplot(221, sharex=ax1)
ax3.plot(x3, y3)
ax3.set_title("ax3")
#plt.setp(ax3.get_xticklabels(), visible=False)


x4 = x2
y4 = y3
ax4 = plt.subplot(222, sharex=ax2, sharey=ax3)
ax4.plot(x4, y4)
ax4.set_title("ax4")
#plt.setp(ax4.get_xticklabels(), visible=False)
#plt.setp(ax4.get_yticklabels(), visible=False)

plt.show()

enter image description here

2
  • That works indeed, I was looking for a generic (non-individual) approach
    – FooBar
    Sep 13, 2016 at 15:10
  • 1
    More code, and much harder to modify than farenorth's answer.
    – naught101
    Feb 14, 2017 at 3:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.