Matplotlib中的图形和坐标轴方法

34

假设我有以下设置:

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 类的层次结构及其相应的方法?

1个回答

63

请使用 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>

在我的系统上(Ubuntu 13.10,ipython 1.1.0,python 2.7.5,matplotlib 1.2.1),我需要在“ax1.set_title(...)”调用后执行“fig1.show()”,以使其产生可见效果。 我猜这是标准行为。 - Rory Yorke
@RoryYorke 是的,你需要默认调用show()。 - zhangxaochen
1
顺便提一下,figure确实有suptitle方法,可以让您在多个子图上放置一个标题。 - physicsmichael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接