Reputation: 626
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
Upvotes: 8
Views: 13250
Reputation: 1
I was trying the same thing and I found ax.annotate
useful.
example:
ax1.annotate('vertical title', (-0.65, 0.5), xycoords = 'axes fraction', rotation = 90, va = 'center', fontweight = 'bold', fontsize = 10)
The coordination was set to axes fraction
and therefore the x positional argument (-0.65 here) set the text left to the Y axis since it was a minus value and set the Y position (0.5 here) at the mid of the Y axis.
Upvotes: 0
Reputation: 68146
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()
Upvotes: 5
Reputation: 17455
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)
Upvotes: 12