当前有效matplotlib版本为:3.4.2。
box()函数概述
box()函数的功能为关闭或显示当前子图的所有边框。边框也被称为box、frame或spines,它由上下左右四条轴脊(spine)构成。
box()函数的签名为matplotlib.pyplot.box(on=None)。
其中on参数的取值为布尔值或None,当取值为True当前子图显示边框,取值为False当前子图关闭边框,取值为None时切换显示、关闭状态。
box()函数原理
根据box()函数源码可知,其工作原理与matplotlib.axes.Axes.set_frame_on()相关,根据Axes对象源码观察可知,关闭的边框与Axes.spines对象有关。
matplotlib.pyplot.box()源码:
def box(on=None):
ax = gca()
if on is None:
on = not ax.get_frame_on()
ax.set_frame_on(on)
matplotlib.axes.Axes.set_frame_on()源码:
def get_frame_on(self):
return self._frameon
def set_frame_on(self, b):
self._frameon = b
self.stale = True
matplotlib.axes.Axes相关源码:
if not (self.axison and self._frameon):
for spine in self.spines.values():
artists.remove(spine)
if self.axison and self._frameon:
self.patch.draw(renderer)
Axes.spines对象
matplotlib.spines.Spine类定义了轴脊。matplotlib.spines.Spines类则是子图中所有matplotlib.spines.Spine对象的容器。
在子图中Axes.spines即matplotlib.spines.Spines类的实例。
Axes.spines提供了类似字典或pandas.DataFrame的接口来访问Spine对象,每个Spine对象可独立控制轴脊的行为,通过Spine对象的set_visible(False)和set_color('none')方法可关闭轴脊。
根据Axes.spines.keys()可知,对应的4个轴脊的键为['left', 'right', 'bottom', 'top']。
Axes.spines访问Spine对象的接口示例如下:
spines['top'].set_visible(False)
spines.top.set_visible(False)
spines[['top', 'right']].set_visible(False)
spines[:].set_visible(False)
案例:演示关闭子图边框

import matplotlib.pyplot as plt
# 默认子图边框样式
plt.subplot(231)
# 关闭当前子图边框
plt.subplot(232)
plt.box()
# 利用ax.set_frame_on关闭边框
plt.subplot(233)
ax = plt.gca()
ax.set_frame_on(False)
# 演示利用spine对象关闭轴脊
plt.subplot(234)
ax = plt.gca()
ax.spines.right.set_color('none')
ax.spines['top'].set_visible(False)
# 利用spines对象索引spine对象的方法
plt.subplot(235)
ax = plt.gca()
ax.spines[['top','left','right']].set_visible(False)
# 去掉y轴刻度
plt.yticks([])
# 利用spines对象索引spine对象的方法
plt.subplot(236)
ax = plt.gca()
ax.spines[:].set_visible(False)
plt.show()
本文介绍Matplotlib中box()函数的使用方法,该函数用于控制图表边框的显示与隐藏。文章详细解释了box()函数的工作原理,并展示了如何通过Spine对象更精细地控制每个轴脊的状态。
1万+





