Is there any way to share Y axis among only part of subplots in matplotlib?

Question:

I have N subplots, and I want to share Y axis for all but one of them. Is it possible?

Asked By: Philipp_Kats

||

Answers:

Yes, you can specify which suplots shares which axis with which axes (this is not a typo I mean this sentence). There’s a sharex and a sharey argument for add_subplot:

For example:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1,2,3,4,5])
y1 = np.arange(5)
y2 = y1 * 2
y3 = y1 * 5

fig = plt.figure()
ax1 = fig.add_subplot(131)                # independant y axis (for now)
ax1.plot(x, y1)
ax2 = fig.add_subplot(132, sharey=ax1)    # share y axis with first plot
ax2.plot(x, y2)
ax3 = fig.add_subplot(133)                # independant y axis
ax3.plot(x, y3)
plt.show()

this will create a plot like this (1st and 2nd share the y axis, but the 3rd does not):

Three plots, the left and middle one share a common y axis. The right plot has an independant y scale.

You can find another example of this in the matplotlib examples “Shared axis Demo”.

Answered By: MSeifert

if you are using this format.

fig, axs = plt.subplots(4,1,sharex=True,figsize=(8,8))

You can try

axs[2].sharey(axs[1])

axs[3].sharey(axs[1])

After each subplot.

Answered By: Yeming Chen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.