Python-Matplotlib将图形标题移动到y轴

时间:2014-01-17 16:57:35

标签: python matplotlib

我目前正在使用python中的matplotlib来绘制一些数据,但是我希望图表的标题位于Y轴上,因为没有足够的空间来容纳一个图形的标题和x轴的标签。其他。我知道我可以将hspace设置为更大的数字但是,我不想这样做,因为我计划将几个图表堆叠在一起,如果我调整hspace,那么图表将是真的简短而难读。 like this http://oi39.tinypic.com/2a4r5i1.jpg

这是我的代码

#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()

提前致谢

2 个答案:

答案 0 :(得分:6)

试试这个:

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)

答案 1 :(得分:4)

matplotlib图上的所有文本元素都有get_positionset_position方法。如果您捕获轴标签的坐标并使用它们来设置标题的坐标加上一点偏移量,那么这很简单。 (编辑:坐标是图的宽度和高度的分数单位。即,(0,0)是左下角的coorner,(1,1)是右上角)

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

enter image description here

相关问题