前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >matplotlib使用教程(二):Axes和subplot

matplotlib使用教程(二):Axes和subplot

原创
作者头像
云时之间
修改2020-11-20 14:52:47
2.3K0
修改2020-11-20 14:52:47
举报
文章被收录于专栏:云时之间云时之间

这一系列文章原载于公众号工程师milter,如果文章对大家有帮助,恳请大家动手关注下哈~


今天继续分析matplotlib中的基本概念。

在上一篇文章中,我们获得了一个figure,并且也大致了解了一下figure的相关设置项。

现在,我们要在figure上画图了。你本来以为直接在figure上画就行了,但事实没这么简单。matplotlib允许我们将一个figure通过栅格系统划分成不同的格子,然后在格子中画图,这样就可以在一个figure中画多个图了。这里的每个格子有两个名称:Axes和subplot。subplot是从figure所有的格子来看的。因为figure要统一管理协调这些格子的位置、间隔等属性,管理协调的方法和属性设置就在subplots的层面进行。

Axes是从作为画图者的我们的角度来定义的,我们要画的点、线等都在Axes这个层面来进行。画图用的坐标系统自然也是在Axes中来设置的。

搞清楚这两个概念后,我们就来看看如何将figure划分格子,并获得我们画图使用的Axes。

通过下边的代码,我们将整个fig划分成了2x2 4个subplots。返回给我们的自然是四个axes,可以通过查看axes证实:

代码语言:javascript
复制
axes = fig.subplots(2,2)

在上图里,我们看到返回的对象是AxesSubplot,它实质上是包含了Axes的Subplot。在使用上,我们完全可以把它当做Axes使用。

如果我们只想在figure上画一幅图,就有两种方法:

代码语言:javascript
复制
axes = fig.subplots(1,1) 
or 
axes = fig.subplots()

此时得到的axes是就是一个AxesSubplot对象。

如果大家观察仔细,会看到里面有3个值,它们确定了subplot在figure中的位置。可以通过下图感受到:

代码语言:javascript
复制
fig = plt.figure()
fig.set_facecolor("green")
axis = fig.subplots()
plt.show()

前两个值实际上是坐标原点相对于figure左下角的位置。第三个值是subplot的宽和高。

figure中还有一个方法:add_subplot。其目的也是将figure划分成栅格,并获取其中某一个。使用方法如下所示:

代码语言:javascript
复制
fig = plt.figure()
ax1 = fig.add_subplot(2, 3, 1)  
fig.add_subplot(232, facecolor="blue")  
fig.add_subplot(233, facecolor="yellow")  
fig.add_subplot(234, sharex=ax1) 
fig.add_subplot(235, facecolor="red") 
fig.add_subplot(236, facecolor="green")  
plt.show()

这里有两个地方需要注意一下。add_subplot(232)和add_subplot(2,3,2)等价的。

另外,如果将最后一个236改成436,你猜会发生什么呢?

答案是如下所示:

可以看到436 相当于将figure重新划分了网格,并将第6个网格设置成绿色。

两种不同的网格划分产生了重叠。这再次体现了matplotlib的灵活性。

最佳的实践是:在开始时就将figure的网格划分好,并不再改变。

Axes 概览

最后,我们还是通览一下Axes的属性:

代码语言:javascript
复制
{'figure': <Figure size 432x288 with1 Axes>,
 '_subplotspec': <matplotlib.gridspec.SubplotSpec at 0x7f039a304bd0>,
 'figbox': Bbox([[0.125, 0.125], [0.9, 0.88]]),
 'rowNum': 0,
 'colNum': 0,
 'numRows': 1,
 'numCols': 1,
 '_stale': True,
 'stale_callback': <function matplotlib.figure._stale_figure_callback(self, val)>,
 '_axes': <matplotlib.axes._subplots.AxesSubplot at 0x7f039b097f90>,
 '_transform': None,
 '_transformSet': False,
 '_visible': True,
 '_animated': False,
 '_alpha': None,
 'clipbox': None,
 '_clippath': None,
 '_clipon': True,
 '_label': '',
 '_picker': None,
 '_contains': None,
 '_rasterized': None,
 '_agg_filter': None,
 '_mouseover': False,
 'eventson': False,
 '_oid': 0,
 '_propobservers': {},
 '_remove_method': <bound method Figure._remove_ax of <Figure size 432x288 with1 Axes>>,
 '_url': None,
 '_gid': None,
 '_snap': None,
 '_sketch': None,
 '_path_effects': [],
 '_sticky_edges': _XYPair(x=[], y=[]),
 '_in_layout': True,
 '_position': Bbox([[0.125, 0.125], [0.9, 0.88]]),
 '_originalPosition': Bbox([[0.125, 0.125], [0.9, 0.88]]),
 '_aspect': 'auto',
 '_adjustable': 'box',
 '_anchor': 'C',
 '_sharex': None,
 '_sharey': None,
 'bbox': <matplotlib.transforms.TransformedBbox at 0x7f039a304a10>,
 'dataLim': Bbox([[inf, inf], [-inf, -inf]]),
 'viewLim': Bbox([[0.0, 0.0], [1.0, 1.0]]),
 'transScale': <matplotlib.transforms.TransformWrapper at 0x7f0399f6ae90>,
 'transAxes': <matplotlib.transforms.BboxTransformTo at 0x7f0399f6a690>,
 'transLimits': <matplotlib.transforms.BboxTransformFrom at 0x7f0399f6a410>,
 'transData': <matplotlib.transforms.CompositeGenericTransform at 0x7f039b091ed0>,
 '_xaxis_transform': <matplotlib.transforms.BlendedGenericTransform at 0x7f039b091310>,
 '_yaxis_transform': <matplotlib.transforms.BlendedGenericTransform at 0x7f039b091610>,
 '_axes_locator': None,
 'spines': OrderedDict([('left', <matplotlib.spines.Spine at 0x7f039ac36050>),
              ('right', <matplotlib.spines.Spine at 0x7f039ac368d0>),
              ('bottom', <matplotlib.spines.Spine at 0x7f039ac36410>),
              ('top', <matplotlib.spines.Spine at 0x7f039ac36810>)]),
 'xaxis': <matplotlib.axis.XAxis at 0x7f039b0913d0>,
 'yaxis': <matplotlib.axis.YAxis at 0x7f039b146510>,
 '_facecolor': 'white',
 '_frameon': True,
 '_axisbelow': 'line',
 '_rasterization_zorder': None,
 '_connected': {},
 'ignore_existing_data_limits': True,
 'callbacks': <matplotlib.cbook.CallbackRegistry at 0x7f039ac36cd0>,
 '_autoscaleXon': True,
 '_autoscaleYon': True,
 '_xmargin': 0.05,
 '_ymargin': 0.05,
 '_tight': None,
 '_use_sticky_edges': True,
 '_get_lines': <matplotlib.axes._base._process_plot_var_args at 0x7f039a2e9850>,
 '_get_patches_for_fill': <matplotlib.axes._base._process_plot_var_args at 0x7f039a58a290>,
 '_gridOn': False,
 'lines': [],
 'patches': [],
 'texts': [],
 'tables': [],
 'artists': [],
 'images': [],
 '_mouseover_set': <matplotlib.cbook._OrderedSet at 0x7f039b02c190>,
 'child_axes': [],
 '_current_image': None,
 'legend_': None,
 'collections': [],
 'containers': [],
 'title': Text(0.5, 1, ''),
 '_left_title': Text(0.0, 1, ''),
 '_right_title': Text(1.0, 1, ''),
 'titleOffsetTrans': <matplotlib.transforms.ScaledTranslation at 0x7f039b80a450>,
 '_autotitlepos': True,
 'patch': <matplotlib.patches.Rectangle at 0x7f039b80a590>,
 'axison': True,
 'fmt_xdata': None,
 'fmt_ydata': None,
 '_navigate': True,
 '_navigate_mode': None,
 '_xcid': 0,
 '_ycid': 0,
 '_layoutbox': None,
 '_poslayoutbox': None}

可以看到,里面有Axes在网格系统中的坐标,所属的figure,还有title,_facecolor等属性。yaxis、xaxis代表坐标轴。

此时,建议大家对比一下Axes和上一讲中的Figure的属性。就可以大致有个感觉,什么样的设置要在哪里去设。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档