Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axes.invert_axis() does not work with sharey=True for matplotlib subplots

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))

enter image description here

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?

like image 957
pbreach Avatar asked Jan 25 '15 03:01

pbreach


People also ask

What is sharey true?

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.

How do you reverse the axis of a subplot in Python?

By using ylim() method ylim() method is also used to invert axes of a plot in Matplotlib.

What does subplots () do 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.


1 Answers

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()
like image 121
snake_charmer Avatar answered Oct 11 '22 11:10

snake_charmer