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

Matplotlib触发pick_event时如何打印colorbar对应数值

实现点击绘图区域获取色条对应映射值

你可以直接在pick_event的回调函数中通过点击坐标换算取值,拿到的结果和NavigationToolbar右下角显示的数值完全一致,实现步骤如下:

  1. 绘图阶段存储每个子图对应的原始像素数组,避免循环中变量被覆盖:
# 新增字典存储子图和对应绘图数据的映射关系
self.subplot_data = {}
for i in range(5):
    for j in range(5):
        sub_image = self.image[i*8:i*8+8, j*8:j*8+8]                           
        ax = plt.subplot(gs[4 - i, j], picker = True, label = self.iD)         
        mesh = ax.pcolormesh(sub_image, vmin=0, vmax=maxZ, cmap="viridis")    
        ax.axis("off")
        ax.set_aspect("equal")
        # 存储当前子图对应的数据
        self.subplot_data[ax] = sub_image

        self.grid[4-i,j] = self.iD
        self.iD += 1
       
fig.subplots_adjust(right=0.71, left=.285, top=0.9, bottom=0.1)
self.cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
self.cbar = fig.colorbar(mesh, cax=self.cbar_ax)
self.cbar.set_label("Charge (Photoelectrons)", rotation=270, size=24, labelpad=24)
self.cbar_ax.tick_params(labelsize=15)
fig.suptitle(f"Run {self.run} Event {self.ev}", fontsize=30)
fig.canvas.mpl_connect("pick_event",self.nextWindow)

self.layout.addWidget(self.static_canvas,1,1)
self.toolBar = NavigationToolbar(self.static_canvas, self)
self.layout.addWidget(self.toolBar,2,1,1,2)
  1. 编写pick_event对应的回调函数nextWindow,通过点击坐标换算数组索引取值:
import numpy as np
from matplotlib.collections import QuadMesh

def nextWindow(self, event):
    # 过滤非pcolormesh的选中元素
    if not isinstance(event.artist, QuadMesh):
        return
    # 获取点击对应的子图和原始子图数据
    current_ax = event.artist.axes
    sub_arr = self.subplot_data[current_ax]
    # 获取鼠标在子图坐标系下的坐标
    mouse_x = event.mouseevent.xdata
    mouse_y = event.mouseevent.ydata
    # 过滤无效坐标(点击在子图外的情况)
    if mouse_x is None or mouse_y is None:
        return
    # pcolormesh的单元格坐标从0开始,向下取整即为对应数组索引
    row = int(np.floor(mouse_y))
    col = int(np.floor(mouse_x))
    # 索引越界判断
    if 0 <= row < sub_arr.shape[0] and 0 <= col < sub_arr.shape[1]:
        target_value = sub_arr[row, col]
        # 打印的数值和NavigationToolbar显示的映射值完全一致
        print(f"拾取位置对应电荷值:{target_value} 光电子")

补充说明:如果你不想手动计算,也可以直接调用子图内置的坐标格式化方法current_ax.format_coord(mouse_x, mouse_y),该方法返回的字符串就是NavigationToolbar右下角显示的完整提示文本,直接解析字符串也能拿到对应数值,手动索引数组的方式更灵活、性能更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 06:46:04