当前有效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()