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()
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?
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.
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.
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()
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()
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