I am trying to make 4 subplots (2x2) with an inverted y axis while also sharing the y axis between subplots. Here is what I get:
import matplotlib.pyplot as plt
import numpy as np
fig,AX = plt.subplots(2, 2, sharex=True, sharey=True)
for ax in AX.flatten():
ax.invert_yaxis()
ax.plot(range(10), np.random.random(10))
It appears that ax.invert_axis()
is being ignored when sharey=True
. If I set sharey=False
I get an inverted y axis in all subplots but obviously the y axis is no longer shared among subplots. Am I doing something wrong here, is this a bug, or does it not make sense to do something like this?
You have applied the share y axis to all of the subplots using the argument sharey=True . There is a handy argument of sharey='row' which will make each row of subplots share the same y axis.
By using ylim() method ylim() method is also used to invert axes of a plot in Matplotlib.
Subplots mean groups of axes that can exist in a single matplotlib figure. subplots() function in the matplotlib library, helps in creating multiple layouts of subplots. It provides control over all the individual plots that are created.
Since you set sharey=True
, all three axes now behave as if their were one. For instance, when you invert one of them, you affect all four. The problem resides in that you are inverting the axes in a for
loop which runs over an iterable of length four, you are thus inverting ALL axes for an even number of times... By inverting an already inverted ax, you simply restore its original orientation. Try with an odd number of subplots instead, and you will see that the axes are successfully inverted.
To solve your problem, you should invert the y-axis of one single subplot (and only once). Following code works for me:
import matplotlib.pyplot as plt
import numpy as np
fig,AX = plt.subplots(2, 2, sharex=True, sharey=True)
## access upper left subplot and invert it
AX[0,0].invert_yaxis()
for ax in AX.flatten():
ax.plot(range(10), np.random.random(10))
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With