【问题标题】:Figure and axes methods in matplotlibmatplotlib 中的图形和轴方法
【发布时间】:2023-03-26 03:01:01
【问题描述】:

假设我有以下设置:

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    改用ax1.set_title('foo')

    ax1.title 返回一个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')
    

    当有多个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(. ..) 呼吁它产生明显的效果。我的猜测是这是标准行为。
    • @RoryYorke 是的,你需要默认调用 show()。
    • FWIW, figure 确实有 suptitle 方法,它允许您将一个标题放在多个子图上。
    猜你喜欢
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多