You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Matplotlib重新映射坐标轴范围并设置自定义刻度

如何在Matplotlib中自定义坐标轴刻度(映射到真实值范围)

这是个很常见的可视化需求,我来给你两种简单易上手的实现方式:

第一步:先确定转换公式的参数

根据你给出的对应关系,我们先算出x_real = a + x * b里的a和b:

  • 当原始x轴为0时,真实值是-4.8573,代入公式可得a = -4.8573
  • 当原始x轴为4时,真实值是12.443,代入公式计算b:
    b = (12.443 - a) / 4
    # 计算结果:b ≈ (12.443 + 4.8573)/4 ≈4.325075
    

方法一:手动设置刻度位置与标签

如果你已经明确想要显示哪些刻度(比如-5、0、10、15),这种方法直接直观:

  1. 列出你想要展示的真实刻度值
  2. 用公式x = (x_real - a)/b计算每个真实刻度对应的原始x轴位置
  3. 用plt.xticks()把原始位置和真实标签绑定起来

修改后的完整代码:

import matplotlib.pyplot as plt

image = [[0.0, 0.0, 0.0, 0.0, 0.0], 
         [0.2, 0.0, 0.1, 0.0 ,0.0], 
         [0.0, 0.0, 0.3, 0.0 ,0.0], 
         [0.0, 0.0, 0.0, 0.0, 0.0], 
         [0.0, 0.0, 0.0, 0.0, 0.0]]

# 定义转换参数
a = -4.8573
b = (12.443 - a) / 4  # ≈4.325075

plt.imshow(image, cmap="plasma", interpolation='nearest')
plt.colorbar()
plt.xlabel("axis x (real values)")
plt.ylabel("axis y")

# 自定义x轴刻度:真实值列表
real_ticks = [-5, 0, 10, 15]
# 计算每个真实值对应的原始x轴位置
original_positions = [(tick - a)/b for tick in real_ticks]
# 设置刻度位置和对应的标签
plt.xticks(ticks=original_positions, labels=real_ticks)

plt.show()

方法二:使用FuncFormatter自动转换(更灵活)

如果希望matplotlib自动处理所有刻度的转换,不用手动计算每个位置,可以用matplotlib.ticker.FuncFormatter实现动态转换:

完整代码:

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

image = [[0.0, 0.0, 0.0, 0.0, 0.0], 
         [0.2, 0.0, 0.1, 0.0 ,0.0], 
         [0.0, 0.0, 0.3, 0.0 ,0.0], 
         [0.0, 0.0, 0.0, 0.0, 0.0], 
         [0.0, 0.0, 0.0, 0.0, 0.0]]

# 定义转换参数
a = -4.8573
b = (12.443 - a) / 4  # ≈4.325075

plt.imshow(image, cmap="plasma", interpolation='nearest')
plt.colorbar()
plt.xlabel("axis x (real values)")
plt.ylabel("axis y")

# 定义转换函数:把原始x值转成真实值,.1f控制显示小数位数
def x_axis_formatter(x, pos):
    return f"{a + x*b:.1f}"

# 给x轴应用自定义格式化器
plt.gca().xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))
# 可选:设置x轴范围,确保覆盖所有图像内容
plt.xlim(-0.5, 4.5)

plt.show()

这种方法的优势是,不管matplotlib自动生成哪些刻度,都会自动转换成真实值,适合需要动态调整刻度的场景。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:56:37