I am currently using matplotlib in python to graph some data, however I want the titles of the graph to be on the Y axis because there is not enough room for both the title of one graph and the x-axis label of the other. I know that I can just set the hspace to a larger number but, I don't want to do this because I am planning on having several charts stacked on top of each other, and if I adjust the hspace then the graph will be really short and harder to read.
Here is my code
#EXAMPLE CODE
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure()
rect = fig.patch
rect.set_facecolor('#31312e')
x = [1,2,3,4,5,6,7,8]
y = [4,3,8,2,8,0,3,2]
z = [2,3,0,8,2,8,3,4]
ax1 = fig.add_subplot(2,1,1, axisbg='gray')
ax1.plot(x, y, 'c', linewidth=3.3)
ax1.set_title('title', color='c')
ax1.set_xlabel('xlabel')
ax1.set_ylabel('ylabel')
ax2 = fig.add_subplot(2,1,2, axisbg='gray')
ax2.plot(x, z, 'c', linewidth=3.3)
ax2.set_xlabel('xlabel')
ax2.set_ylabel('ylabel')
plt.show()
Thanks In advance
Try with this:
ax1.set_title('title1', color='c', rotation='vertical',x=-0.1,y=0.5)
ax2.set_title('title2', color='c', rotation='vertical',x=-0.1,y=0.5)
All text elements on a matplotlib figure have get_position
and set_position
methods. It's it's pretty simple to do if you capture the coordinates of the axes label and use those to set the coords of the title plus a little bit of offset. (edit: the coords are in the units of fractions of the figure width and height. i.e., (0,0) is the lower left coorner and (1,1) is the upper right corner)
fig, axes = plt.subplots(nrows=2)
ax0label = axes[0].set_ylabel('Axes 0')
ax1label = axes[1].set_ylabel('Axes 1')
title = axes[0].set_title('Title')
offset = np.array([-0.15, 0.0])
title.set_position(ax0label.get_position() + offset)
title.set_rotation(90)
fig.tight_layout()
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