如何在matplotlib绘制带插图的图表时手动修改坐标轴刻度值
Matplotlib带插图(inset)的坐标轴刻度格式化方法

操作核心:你只需要分别拿到主图、插图对应的Axes对象,对每个对象单独设置刻度格式即可,操作逻辑和普通单图的坐标轴修改完全一致。
以下是两种常用实现方案:
方案1:自动格式化所有刻度为整数(推荐)
该方案不需要手动指定刻度值,会自动将所有现有刻度的小数位去除,适配动态刻度场景。
依赖导入:
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes from matplotlib.ticker import FormatStrFormatter
核心操作代码:
# 主图刻度格式化,ax_main替换为你的主图Axes对象名 ax_main.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax_main.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) # 插图刻度格式化,ax_inset替换为你的插图Axes对象名 ax_inset.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax_inset.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
完整可运行测试示例:
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes from matplotlib.ticker import FormatStrFormatter import numpy as np # 生成示例数据 x = np.linspace(0, 1, 100) y = 1 + x**2 # 创建主图 fig, ax_main = plt.subplots(figsize=(6, 4)) ax_main.plot(x, y) # 创建右上角插图 ax_inset = inset_axes(ax_main, width="30%", height="30%", loc="upper right") ax_inset.plot(x, y) # 统一格式化主图和插图的刻度为整数 ax_main.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax_main.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax_inset.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax_inset.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) plt.show()
方案2:手动指定固定刻度和标签
适合需要严格控制显示的刻度值的场景:
# 主图刻度设置 ax_main.set_xticks([0, 1]) ax_main.set_xticklabels(['0', '1']) ax_main.set_yticks([1, 2]) ax_main.set_yticklabels(['1', '2']) # 插图刻度设置 ax_inset.set_xticks([0, 1]) ax_inset.set_xticklabels(['0', '1']) ax_inset.set_yticks([1, 2]) ax_inset.set_yticklabels(['1', '2'])
内容的提问来源于stack exchange,提问作者Jo Bi
相关产品推荐
相关产品推荐

