Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing a yaxis label with two of three subplots in pyplot

I have the following code which produces the plot shown.

mport matplotlib.pyplot as plt 
import matplotlib.gridspec as gridspec
import numpy as np

One = range(1,10)
Two = range(5, 14) 
l = len(One)
fig = plt.figure(figsize=(10,6))
gs = gridspec.GridSpec(3, 1, height_ratios=[5, 3, 3]) 

ax0 = plt.subplot(gs[0])
ax0.bar(range(l), Two)
plt.ylabel("Number of occurrence")

ax1 = plt.subplot(gs[1], sharey=ax0)
ax1.bar(range(l), Two)

ax2 =  plt.subplot(gs[2])
ax2.bar(range(l), One)

plt.show()

enter image description here

I want the ylabel (" Number of occurrence") to be shared between first and second plot, that is, it should occur in the center left of first and second plot. How do I do that?

like image 707
DurgaDatta Avatar asked Dec 18 '13 14:12

DurgaDatta


People also ask

How do you plot 3 subplots in Python?

To create multiple plots use matplotlib. pyplot. subplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid.

How do you separate subplots in Python?

Using subplots_adjust() method to set the spacing between subplots. We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots.


2 Answers

The best way I can think of is to add the text to the figure itself and position it at the center (figure coordinates of 0.5) like so

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

One = range(1,10)
Two = range(5, 14)
l = len(One)
fig = plt.figure(figsize=(10,6))
gs = gridspec.GridSpec(3, 1, height_ratios=[5, 3, 3])

ax0 = plt.subplot(gs[0])
ax0.bar(range(l), Two)

ax1 = plt.subplot(gs[1], sharey=ax0)
ax1.bar(range(l), Two)

ax2 =  plt.subplot(gs[2])
ax2.bar(range(l), One)

fig.text(0.075, 0.5, "Number of occurrence", rotation="vertical", va="center")

plt.show()
like image 69
cimarron Avatar answered Oct 21 '22 06:10

cimarron


You can also adjust the position manually, using the y parameter of ylabel:

import matplotlib.pyplot as plt 
import matplotlib.gridspec as gridspec
import numpy as np

One = range(1,10)
Two = range(5, 14) 
l = len(One)
fig = plt.figure(figsize=(10,6))
gs = gridspec.GridSpec(3, 1, height_ratios=[5, 3, 3]) 

ax0 = plt.subplot(gs[0])
ax0.bar(range(l), Two)
plt.ylabel("Number of occurrence", y=-0.8)          ##  ← ← ← HERE

ax1 = plt.subplot(gs[1], sharey=ax0)
ax1.bar(range(l), Two)

ax2 =  plt.subplot(gs[2])
ax2.bar(range(l), One)

plt.show()

enter image description here

like image 36
Luis Avatar answered Oct 21 '22 06:10

Luis