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

Matplotlib+mpl_scatter_density导致窗口随鼠标坐标异常缩放求助

解决Matplotlib Toolmanager模式下mpl_scatter_density坐标框异常缩放问题

针对你遇到的两个核心问题——鼠标进出绘图区时窗口异常缩放、无法修改/移除密度值行,这里提供几个实用解决方案:

1. 完全移除密度值行

mpl_scatter_density的额外密度行是通过ScatterDensityAxes的format_coord方法添加的,直接替换这个方法为普通坐标格式即可移除:

# 创建绘图轴后,替换format_coord
ax.format_coord = lambda x, y: f'x={x:.4f} y={y:.4f}'

这样鼠标悬停时只会显示x/y坐标,不会出现额外的密度行,从根源上解决工具栏高度变化导致的窗口缩放问题。

2. 保留密度值但避免窗口缩放

如果需要保留密度信息,可通过以下两种方式解决:

2.1 将密度值与坐标合并为一行

修改format_coord方法,把密度值和x/y坐标放在同一行,确保状态栏高度始终不变:

def custom_format_coord(x, y):
    # 获取原始坐标字符串
    coord_str = ax.format_coord_base(x, y)
    # 获取当前点的密度值
    density = ax.get_density_at_point(x, y)
    if density is not None:
        return f'{coord_str} | 密度={density:.2f}'
    return coord_str

# 替换轴的format_coord方法
ax.format_coord = custom_format_coord

2.2 固定状态栏高度

即使字体变大或行数变化,强制固定状态栏的高度也能阻止窗口缩放:

# 获取Toolmanager的状态栏并设置固定高度
tm = fig.canvas.manager.toolmanager
if tm.status_bar:
    tm.status_bar.setFixedHeight(30)  # 根据字体大小调整合适数值

3. 正确设置坐标框字体大小

之前font.size设置无效可能是因为时机不对——必须在创建figure之前设置rcParams:

import matplotlib.pyplot as plt

# 提前配置参数,放在创建figure之前
plt.rcParams.update({
    'toolbar': 'toolmanager',
    'font.size': 8  # 调整为合适的小字体
})

完整测试代码

整合以上方案的示例代码(以移除密度行为例):

import matplotlib.pyplot as plt
import mpl_scatter_density
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

# 提前配置rc参数
plt.rcParams.update({
    'toolbar': 'toolmanager',
    'font.size': 8
})

# 自定义白底Viridis色卡
white_viridis = LinearSegmentedColormap.from_list('white_viridis', [
    (0, '#ffffff'),
    (1e-20, '#440053'),
    (0.2, '#404388'),
    (0.4, '#2a788e'),
    (0.6, '#21a784'),
    (0.8, '#78d151'),
    (1, '#fde624'),
], N=256)

# 生成测试数据
x = np.random.normal(size=100000)
y = x * 3 + np.random.normal(size=100000)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='scatter_density')
density = ax.scatter_density(x, y, cmap=white_viridis)
fig.colorbar(density, label='Number of points per pixel')

# 移除密度行
ax.format_coord = lambda x, y: f'x={x:.4f} y={y:.4f}'

# 固定状态栏高度
tm = fig.canvas.manager.toolmanager
if tm.status_bar:
    tm.status_bar.setFixedHeight(25)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 17:39:56