【问题标题】:How do you get the current figure number in Python's matplotlib?如何在 Python 的 matplotlib 中获取当前图形编号?
【发布时间】:2017-07-08 11:00:36
【问题描述】:

我正在使用一个示例脚本来展示如何在图形之间来回切换。我在这里找到了这个例子:http://matplotlib.org/examples/pylab_examples/multiple_figs_demo.html 当我尝试打印数字时,我得到的是“Figure(640x480)”,而不是我期望的数字 1。你是怎么得到号码的?

# Working with multiple figure windows and subplots
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)

plt.figure(1)
plt.subplot(211)
plt.plot(t, s1)
plt.subplot(212)
plt.plot(t, 2*s1)

plt.figure(2)
plt.plot(t, s2)

# now switch back to figure 1 and make some changes
plt.figure(1)
plt.subplot(211)
plt.plot(t, s2, 's')
ax = plt.gca()
ax.set_xticklabels([])

# Return a list of existing figure numbers.
print "Figure numbers are = " + str(plt.get_fignums())
print "current figure = " + str(plt.gcf())
print "current axes   = " + str(plt.gca())

plt.show()

这是输出:

Figure numbers are = [1, 2]
current figure = Figure(640x480)
current axes   = Axes(0.125,0.53;0.775x0.35)

【问题讨论】:

    标签: python matplotlib figure


    【解决方案1】:

    Figure 对象有一个number 属性,所以可以通过

    >>> plt.gcf().number
    

    【讨论】:

    • 是的,这行得通。你怎么知道的?即使知道该怎么做,我也找不到任何文档。
    • 您还可以使用文本字符串而不是数字创建图形,例如 plt.figure("first")。当您在数字之间切换时,这可能比数字更容易记住。 plt.gcf().number 仍然给出整数“1”,所以它必须是自动编号。
    • @R.Wayne 老实说,我以前并不知道,但我认为有这样一个属性(我认为“有根据的猜测”这个词非常适用)。所以我检查了dir(plt.gcf()),它显示了number 属性。 help(pyplot.figure) 还提供以下信息:[...] 图形对象在 number 属性中保存此数字。 通常,只需检查您所使用的任何对象上的 dir(...) 是一个好的开始想要从中检索属性。 help(...) 通常也很有用!
    • @R.Wayne pyplot 似乎在内部为每个数字存储了一个数字,即使您为其分配了一个字符串,并且只要您不提供数字,它就会从已经存在的最大数字自动递增。示例:plt.figure(3); plt.gcf().number => 3plt.figure(1); plt.gcf().number => 1; plt.figure('a'); plt.gcf().number => 4(而不是 2,它仍然是“免费的”)。
    猜你喜欢
    • 2011-12-20
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    相关资源
    最近更新 更多