2014-02-19 54 views
9

说我有以下设置:图和轴在matplotlib方法

import matplotlib.pyplot as plt 
import numpy as np 

x = np.arange(5) 
y = np.exp(x) 
fig1 = plt.figure() 
ax1 = fig1.add_subplot(111) 
ax1.plot(x, y) 

我想一个标题添加到情节(或到副区)。

我想:

> fig1.title('foo') 
AttributeError: 'Figure' object has no attribute 'title' 

> ax1.title('foo') 
TypeError: 'Text' object is not callable 

如何使用面向对象的编程接口matplotlib设置这些属性?

更一般地说,我可以在哪里找到matplotlib中类的层次结构及其相应的方法?

回答

22

使用ax1.set_title('foo')代替

ax1.title返回matplotlib.text.Text对象:

In [289]: ax1.set_title('foo') 
Out[289]: <matplotlib.text.Text at 0x939cdb0> 

In [290]: print ax1.title 
Text(0.5,1,'foo') 

您还可以添加一个居中标题图中,当有多个AxesSubplot

In [152]: fig, ax=plt.subplots(1, 2) 
    ...: fig.suptitle('title of subplots') 
Out[152]: <matplotlib.text.Text at 0x94cf650> 
+0

在我的系统( Ubuntu 13.10,ipython 1.1.0,python 2.7.5,matplotlib 1.2.1)我需要在'ax1.set_title(...)c之后做一个'fig1.show()'所有这一切都会带来明显的效果。我的猜测是这是标准行为。 –

+0

@RoryYorke是的,你需要默认调用show()。 – zhangxaochen

+1

FWIW,'figure'确实有'suptitle'方法,它允许您将一个标题放在多个子图上。 – physicsmichael