python - plt.show() 第二次使用时什么都不做

标签 python matplotlib

我刚开始在 Data Camp 上使用 python 学习数据科学,在使用 matplotlib.pyplot 中的函数时我注意到了一些东西

import matplotlib.pyplot as plt

year = [1500, 1600, 1700, 1800, 1900, 2000]
pop = [458, 580, 682, 1000, 1650, 6,127]

plt.plot(year, pop)

plt.show() # Here a window opens up and shows the figure for the first time

但是当我尝试再次显示它时,它没有..

plt.show() # for the second time.. nothing happens

而且我必须重新输入 show() 上方的行才能再次显示图形

这是正常现象还是问题?

注意:我使用的是REPL

最佳答案

回答

是的,这是 matplotlib 图形的正常预期行为。


说明

当您运行 plt.plot(...) 时,您一方面创建了实际绘图的 lines 实例:

>>> print( plt.plot(year, pop) )
[<matplotlib.lines.Line2D object at 0x000000000D8FDB00>]

...另一方面是一个 Figure 实例,它被设置为“当前图形”并可通过 plt.gcf() 访问(“获取当前数字"):

>>> print( plt.gcf() )
Figure(432x288)

线条(以及您可能添加的其他绘图元素)都放置在当前图形中。调用 plt.show() 时,会显示当前图形,然后清空 (!),这就是第二次调用 plt.show() 的原因 不绘制任何内容。


标准解决方法

解决此问题的一种方法是显式保留当前的 ​​Figure 实例,然后使用 fig.show() 直接显示它,如下所示:

plt.plot(year, pop)
fig = plt.gcf()  # Grabs the current figure

plt.show()  # Shows plot
plt.show()  # Does nothing

fig.show()  # Shows plot again
fig.show()  # Shows plot again...

一个更常用的替代方法是在开始时明确初始化当前图形,然后再执行任何绘图命令。

fig = plt.figure()   # Initializes current figure
plt.plot(year, pop)  # Adds to current figure

plt.show()  # Shows plot
fig.show()  # Shows plot again

这通常与图形的一些附加参数的规范相结合,例如:

fig = plt.figure(figsize=(8,8))

对于 Jupyter Notebook 用户

fig.show() 方法在 Jupyter Notebooks 的上下文中可能不起作用,而是会产生以下警告并且不显示绘图:

C:\redacted\path\lib\site-packages\matplotlib\figure.py:459: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure

幸运的是,只需在代码单元末尾写入 fig(而不是 fig.show()),就会将图形推送到单元格的输出并显示它.如果您需要在同一个代码单元中多次显示它,您可以使用 display 函数实现相同的效果:

fig = plt.figure()   # Initializes current figure
plt.plot(year, pop)  # Adds to current figure

plt.show()  # Shows plot
plt.show()  # Does nothing

from IPython.display import display
display(fig)  # Shows plot again
display(fig)  # Shows plot again...

使用函数

想要多次显示一个图形的一个原因是每次都要进行各种不同的修改。这可以使用上面讨论的 fig 方法来完成,但对于更广泛的绘图定义,通常更容易简单地将基本图形包装在一个函数中并重复调用它。

例子:

def my_plot(year, pop):
    plt.plot(year, pop)
    plt.xlabel("year")
    plt.ylabel("population")

my_plot(year, pop)
plt.show()  # Shows plot

my_plot(year, pop)
plt.show()  # Shows plot again

my_plot(year, pop)
plt.title("demographics plot")
plt.show()  # Shows plot again, this time with title

关于python - plt.show() 第二次使用时什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50452455/

相关文章:

python - 在 PYPI Pip 下载中找不到 Pywin31-214

python - AWS Lambda 包部署

python - 在 Bokeh 中调整 matplotlib 标记大小?

python - Matplotlib 3D 图 - 输入数据的二维格式?

python - 与 matplotlib 交互

python - ViewDoesNotExist : Error

python - 在 python2 中编译 bz2 支持

python - 如何正确地将对数比例图与背景图像结合起来?

python - 给定起始颜色和中间颜色,如何获得剩余颜色? (Python)

python - 根据正则表达式结果使用 python 拆分 CSV