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

Python中修改mplcursor光标标注文本及多子图适配方法

修改mplcursors光标标注文本及多子图场景实现方法

单子图场景修改方法

要将光标标注从默认的x:<>, y:<>改为自定义文本,核心是利用mplcursors.cursor()的formatter参数传入自定义格式化函数。该函数可获取点击点的坐标值及对应坐标轴的标签,生成所需的标注内容。

修改后的完整代码:

import matplotlib.pyplot as plt
import numpy as np
import mplcursors

data = np.outer(range(10), range(1, 5))

fig, ax = plt.subplots()
lines = ax.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\nAnnotations can be dragged.")
plt.xlabel('xaxis')
plt.ylabel('ylabel')

# 自定义标注格式化函数
def format_annotation(sel):
    x_val = sel.target[0]
    y_val = sel.target[1]
    x_label = sel.axes.get_xlabel()
    y_label = sel.axes.get_ylabel()
    return f"{x_label}: {x_val:.2f}, {y_label}: {y_val:.2f}"

mplcursors.cursor(lines, formatter=format_annotation)

plt.show()

关键说明

  • sel.target:获取点击点的(x,y)坐标值
  • sel.axes.get_xlabel()/get_ylabel():动态获取当前坐标轴的标签,避免硬编码
  • 返回的字符串可根据需求调整数值精度(示例中保留2位小数)

多子图场景实现方法

多子图场景下,可通过两种方式实现自定义标注:统一应用格式化函数,或为每个子图单独设置。

方式1:统一应用格式化函数

如果所有子图的标注规则一致,直接将所有坐标轴对象传入mplcursors.cursor()即可:

import matplotlib.pyplot as plt
import numpy as np
import mplcursors

# 生成测试数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建1行2列的子图
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

# 绘制子图1
ax1.plot(x, y1)
ax1.set_xlabel('角度(rad)')
ax1.set_ylabel('sin值')
ax1.set_title('正弦曲线')

# 绘制子图2
ax2.plot(x, y2)
ax2.set_xlabel('角度(rad)')
ax2.set_ylabel('cos值')
ax2.set_title('余弦曲线')

# 复用单图的格式化函数
def format_annotation(sel):
    x_val = sel.target[0]
    y_val = sel.target[1]
    x_label = sel.axes.get_xlabel()
    y_label = sel.axes.get_ylabel()
    return f"{x_label}: {x_val:.2f}, {y_label}: {y_val:.2f}"

# 为所有子图应用光标和格式化规则
mplcursors.cursor([ax1, ax2], formatter=format_annotation)

plt.tight_layout()
plt.show()

方式2:为每个子图单独设置

若不同子图需要不同的标注格式,可为每个坐标轴单独创建光标并指定格式化函数:

# 子图1自定义标注
mplcursors.cursor(ax1, formatter=lambda sel: f"正弦曲线 - 角度: {sel.target[0]:.1f}, 值: {sel.target[1]:.3f}")
# 子图2自定义标注
mplcursors.cursor(ax2, formatter=lambda sel: f"余弦曲线 - 角度: {sel.target[0]:.1f}, 值: {sel.target[1]:.3f}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:35:16