何时需要 `plt.show()` 来显示绘图,何时不需要?
当没有交互式绘图时,`plt.show()` 会有所帮助。
如果是交互式的,`fig.show()` 将有助于显示所有图形。
让我们来看一个例子,观察`plt.show()` 和 `fig.show()` 之间的区别。
步骤
打开iPython shell。
设置图形大小并调整子图之间和周围的填充。
创建一个新图形或激活现有图形。
使用`plot()` 方法绘制一条线。
使用`show()` 方法显示图形。
要显示图形,请使用带有`block=False` 的`show()` 方法。
示例
import numpy as np from matplotlib import pyplot as plt # Set the figure size plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # Create a new figure fig = plt.figure() # Plot a line plt.plot(np.linspace(-5, 5, 100)) fig.show() plt.show(block=False)
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
它将产生以下输出:
只有在交互模式下才能获得此输出。当没有交互式绘图时,带有`block=True` 的`plt.show()` 将显示输出。
广告