📜  如何在Python中使用 Matplotlib 创建一个空图?

📅  最后修改于: 2022-05-13 01:55:42.899000             🧑  作者: Mango

如何在Python中使用 Matplotlib 创建一个空图?

显式创建图形是一种与 matplotlib 交互的面向对象风格。该图形是创建绘图的基本构建块,因为 Matplotlib 在图形上绘制我们的数据。该图跟踪所有其他组件,例如子轴、图例、标题、轴等。

创建空图的步骤:

  • 首先,我们导入 matplotlib 库,特别是 matplotlib 的 pyplot 模块。
  • 然后我们使用 plt.figure() 创建一个图形对象,并通过将其设置为等于 'fig' 变量来保持对该对象的引用。这个图形对象是空的,因为我们没有添加任何图形组件,如轴、图例、轴等。
  • 我们正在使用 jupyter notebook,我们必须将后端更改为 ipympl 交互式后端 ,就像默认后端显示非 GUI 后端错误一样。

要安装 ipympl,请在终端中运行此命令:

对于 conda 环境。

conda install ipympl -c conda-forge

对于普通的Python终端:

pip install ipympl

下面是实现:

示例1:

Python3
# importing the library
import matplotlib
  
# Enabling interactive backend ipympl in
# jupyter notebook or you can use
# any other backend
%matplotlib ipympl
  
import matplotlib.pyplot as plt
  
# an empty figure with no axes
fig = plt.figure()


Python3
# using different backend
import matplotlib
%matplotlib tk
import matplotlib.pyplot as plt
  
#creating a figure
fig = plt.figure()


Python3
import matplotlib
  
# changing backend
%matplotlib tk
import matplotlib.pyplot as plt
  
# saving the figure
plt.savefig('testfigure.png',
            dpi = 100)
  
# displaying the figure
plt.show()


输出:

示例 2:

您还可以使用另一个交互式后端来显示您的图形,例如 TkAgg(需要安装 TkInter)。

蟒蛇3

# using different backend
import matplotlib
%matplotlib tk
import matplotlib.pyplot as plt
  
#creating a figure
fig = plt.figure()

输出 :

图2_gfg

注意:在不同的编辑器或Python shell 中显示图形需要你使用后端。

show() 方法也显示一个空图,但您必须在使用 show() 命令之前保存该图。

例子 :

在下面的例子中,我使用了 figsize 属性来改变图形的大小。

蟒蛇3

import matplotlib
  
# changing backend
%matplotlib tk
import matplotlib.pyplot as plt
  
# saving the figure
plt.savefig('testfigure.png',
            dpi = 100)
  
# displaying the figure
plt.show()

输出 :

图3_gfg