matplotlib中的层次结构

2024-09-28 16:59:01 发布

您现在位置:Python中文网/ 问答频道 /正文

根据this文章,matplotlib中的所有内容都是按层次结构组织的。层次结构的顶部是matplotlib“状态机环境”,它由matplotlib.pyplot模块提供。在这个层次上,简单的函数用于将绘图元素(线、图像、文本等)添加到当前图形的当前轴上。层次结构中的下一级是面向对象接口的第一级,其中pyplot仅用于图形创建等少数功能,用户显式地创建并跟踪图形和轴对象。在这个级别,用户使用pyplot创建图形,通过这些图形,可以创建一个或多个axis对象。这些轴对象随后用于大多数打印操作。 也有其他的术语,如图形,轴,轴,艺术家(有一个很好的图片,解释了所有这些,在提到的页面)。总而言之:

  1. 所有内容都属于matplotlib.pyplot模块
  2. 图形-跟踪所有的子轴,少量的“特殊”艺术家(标题、人物传说等)
  3. 轴-具有数据空间的图像区域-属于图形
  4. 轴-标记记号(x、y、z坐标等)的字符串属于轴
  5. 艺术家-你在人物身上看到的一切(甚至是人物、轴和轴对象)都属于图形

创建新地物的最简单方法是使用pyplot:

fig = plt.figure()  # an empty figure with no axes
fig, ax_lst = plt.subplots(2, 2)  # a figure with a 2x2 grid of Axes

我经常看到这两种方法可以互换使用,我希望它们基本上是等价的。但是使用fig, ax = plt.subplots()和使用fig = plt.figure()和{}无法获得相同的结果

以下是我的实验,针对plt.figure()

^{pr2}$

以下是我的实验,针对plt.subplots()

In [1]: from mpl_toolkits.mplot3d import Axes3D

In [2]: import matplotlib.pyplot as plt

In [3]: fig, ax = plt.subplots()

In [4]: fig
Out[4]: <matplotlib.figure.Figure at 0x7f3dcf96e710>

In [5]: ax
Out[5]: <matplotlib.axes._subplots.AxesSubplot at 0x7f3dced564d0>

In [6]: 

如您所见,第一个创建matplotlib.axes._subplots.Axes3DSubplot对象,而第二个创建matplotlib.axes._subplots.AxesSubplot对象。我一直在搜索help(plt.subplots)以查找projection关键字,但没有找到任何内容。因此,我尝试对plt.subplots使用与fig.add_subplot相同的参数,但我得到以下错误:

In [7]: fig, ax = plt.subplots(111, projection='3d')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-a905adad48f5> in <module>()
----> 1 fig, ax = plt.subplots(111, projection='3d')

/usr/lib/python2.7/dist-packages/matplotlib/pyplot.pyc in subplots(nrows, ncols, sharex, sharey, squeeze, subplot_kw, gridspec_kw, **fig_kw)
   1076         gridspec_kw = {}
   1077 
-> 1078     fig = figure(**fig_kw)
   1079     gs = GridSpec(nrows, ncols, **gridspec_kw)
   1080 

/usr/lib/python2.7/dist-packages/matplotlib/pyplot.pyc in figure(num, figsize, dpi, facecolor, edgecolor, frameon, FigureClass, **kwargs)
    433                                         frameon=frameon,
    434                                         FigureClass=FigureClass,
--> 435                                         **kwargs)
    436 
    437         if figLabel:

/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.pyc in new_figure_manager(num, *args, **kwargs)
     78     """
     79     FigureClass = kwargs.pop('FigureClass', Figure)
---> 80     figure = FigureClass(*args, **kwargs)
     81     return new_figure_manager_given_figure(num, figure)
     82 

TypeError: __init__() got an unexpected keyword argument 'projection'

问题:

fig, ax = plt.subplots()fig = plt.figure(); ax = fig.add_subplot(111, projection='3d')的等价物,如果是,我如何在示例中使用fig, ax = plt.subplots()?在

在上述页面上还有以下代码:

#!/bin/env python

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2, 100)

# The first call to plt.plot will automatically create the necessary figure and axes to achieve the desired plot.
plt.plot(x, x, label='linear')

# Subsequent calls to plt.plot re-use the current axes and each add another line.
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')

# Setting the title, legend, and axis labels also automatically use the current axes and set the title, create the legend, and label the axis respectively.
plt.xlabel('x label')
plt.ylabel('y label')

plt.title("Simple Plot")

plt.legend()

plt.show()

如您所见,没有这样的函数fig = plt.figure()也没有fig, ax_lst = plt.subplots(2, 2)

问题:

在这个例子中,层次结构是如何维护的,图形是默认创建的还是发生了什么?在


Tags: the对象in图形plotmatplotlibfigplt
1条回答
网友
1楼 · 发布于 2024-09-28 16:59:01

问题1

我认为您已经向您自己展示了这些命令并不是完全等价的,只是希望得到一些保证。在

要做你想做的事情-你可以通过建立一个子时隙参数字典并将它们传递给projectionadd_subplot()调用,这些调用是“隐藏”使用的

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
subplot_args = {'projection':'3d'}
fig, ax = plt.subplots(subplot_kw=subplot_args)

对命名参数subplot_kw的使用进行了描述in the docs here。在

问题2

图形轴等都是由第一行开始的plt.plot创建的。pyplot模块正在维护状态并重用相同的图形实例和轴实例,直到您调用plt.show()。在

请注意,就目前情况而言,您没有这些实例的句柄。如果你想的话,你总是可以得到一个句柄,例如打电话

^{pr2}$

以及

ax = plt.gca()

其中^{} and ^{}分别是get current figure和get current axies。这是基于matplotlib最初基于的matlab功能。在

如果你真的很想看看自动创建是如何完成的-这都是开源的。您可以看到对plot()的调用通过调用the code here中的gca()创建了一个Axes实例。这又是calls ^{},它looks for a ^{}(这是实际维护状态的东西)。如果存在一个,它将返回它正在管理的图形,否则它将使用^{}创建一个新的图形。同样,这个过程在某种程度上继承了matlab,在matlab中,在任何绘图操作之前,初始调用通常是figure。在


附录

我想您可能想知道的是如何使用matplotlib.pyplot函数,比如plt.plot()等,让您访问文档中描述的层次结构。答案是,如果你想要真正的细粒度控制,有时候就不需要了

fig, ax = plt.subplots()

模式或类似的,以便他们有直接处理图形和轴对象的句柄,并可以随意操作它们。在

相关问题 更多 >