0

I took a look to several discussions on the site and I can't find what I want. I want to set a common xlabel to 2 subplots on the same line like this :

enter image description here

I tried set_xlabel(), text(), but for the first it didn't work, and for the second I can't put the text at the bottom center.

And I would like to optimize the code, if someone knows how.

My code :

plt.subplot(121)
plt.barh(range(1, len(y)+1), y)
plt.yticks([i+1.5 for i in range(7)], range(7))
plt.xlim(0, xmax)

plt.ylabel("Y label")

plt.subplot(122)
plt.barh(range(1, len(y2)+1), y2, color="r")
plt.yticks([i+1.5 for i in range(7)], range(7))
plt.xlim(0, xmax)
Eiffel
  • 153
  • 4
Biopy
  • 167
  • 1
  • 5
  • 15
  • 2
    Possible duplicate of [Common xlabel/ylabel for matplotlib subplots](http://stackoverflow.com/questions/16150819/common-xlabel-ylabel-for-matplotlib-subplots) – Diziet Asahi Feb 23 '17 at 10:50
  • Already checked and already tried, but didn't work. For a 3x3 subplots, it's easy to center the xlabel, but for a 1x2 subplots, I don't know. – Biopy Feb 23 '17 at 11:01
  • 1
    please explain why/how it "didn't work" – Diziet Asahi Feb 23 '17 at 11:04
  • The accepted answer from the [linked question](http://stackoverflow.com/questions/16150819/common-xlabel-ylabel-for-matplotlib-subplots) works for **any** number of subplots. So it cannot be easy for 3x3 but not easy for 1x2. – ImportanceOfBeingErnest Feb 23 '17 at 11:46
  • @Diziet Asahi, It gave me errors – Biopy Feb 23 '17 at 13:00

1 Answers1

0

As can be seen from e.g. this question, you can simply set some text in the middle of the figure. (This does not depend on how many subplots there are in the figure).

plt.gcf().text(0.5,0.04,"common xlabel for subplots on the same line", ha="center")

Complete example:

import matplotlib.pyplot as plt
import numpy as np

y = np.random.randint(100,833, size=(7,2))

plt.subplot(121)
plt.barh(range(1, len(y)+1), y[:,0])
plt.yticks([i+1.5 for i in range(len(y))], range(len(y)))
plt.xlim(0, 1000)

plt.ylabel("Y label")

plt.subplot(122)
plt.barh(range(1, len(y)+1), y[:,1], color="r")
plt.yticks([i+1.5 for i in range(len(y))], range(len(y)))
plt.xlim(0, 1000)

plt.gcf().text(0.5,0.04,"common xlabel for subplots on the same line", ha="center")
plt.show()


The other option would be to create a new axes, with the frame turned off and provide a label to it, see e.g. this question
ax = plt.gcf().add_subplot(111, frameon=False)
ax.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')
ax.set_xlabel('common xlabel for subplots on the same line', labelpad=8)
Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Actually when I used text(), the text was superimposed to the graphs, and even if I change x et y coordinates, it wasn't placed where I wanted. Maybe because of the gcf() you add. – Biopy Feb 23 '17 at 13:08