matplotlib之pyplot模块——显示/关闭子图边框(轴脊)(box())

本文介绍Matplotlib中box()函数的使用方法,该函数用于控制图表边框的显示与隐藏。文章详细解释了box()函数的工作原理,并展示了如何通过Spine对象更精细地控制每个轴脊的状态。

当前有效matplotlib版本为:3.4.2

box()函数概述

box()函数的功能为关闭或显示当前子图的所有边框。边框也被称为boxframespines,它由上下左右四条轴脊(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.spinesmatplotlib.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()
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值