Python matplotlib 中的图形和坐标轴方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21885176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:48:46  来源:igfitidea点击:

Figure and axes methods in matplotlib

pythonmatplotlib

提问by Amelio Vazquez-Reina

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?

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

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

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

采纳答案by zhangxaochen

use ax1.set_title('foo')instead

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

ax1.titlereturns a matplotlib.text.Textobject:

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

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

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

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