Figure and axes methods in matplotlib

Question:

Say I have the following setup:

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)

I would like to add a title to the plot (or to the subplot).

I tried:

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

and

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

How can I use the object-oriented programming interface to matplotlib to set these attributes?

More generally, where can I find the hierarchy of classes in matplotlib and their corresponding methods?

Answers:

use ax1.set_title('foo') instead

ax1.title returns a matplotlib.text.Textobject:

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

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

You can also add a centered title to the figure when there are multiple AxesSubplot:

In [152]: fig, ax=plt.subplots(1, 2)
     ...: fig.suptitle('title of subplots')
Out[152]: <matplotlib.text.Text at 0x94cf650>
Answered By: zhangxaochen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.