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

Matplotlib使用set_xticklabels后鼠标悬停X轴值为空问题排查

问题原因分析

你的第二段代码里,ax.set_xticks(time_series)这一步犯了关键错误。

当Matplotlib处理字符串类型的X轴数据时,底层会把这些字符串当作分类标签,实际对应的X轴坐标是0、1、2、3这类连续的数值索引,而非字符串本身。set_xticks()方法需要接收的是这些数值型的坐标位置,不是字符串标签。你直接传入字符串列表time_series,Matplotlib无法将其映射到正确的坐标位置,导致悬停时无法匹配到对应的X轴标签,因此显示为空。

而第一段代码里的plt.xticks(x_ticks, rotation=45, ...)能正常工作,是因为plt.xticks()在接收字符串作为第一个参数时,会自动帮你映射到对应的分类坐标位置,相当于替你完成了range(len(x_ticks))的转换。

修复方案

修改setup_axes函数里的刻度设置部分即可:

def setup_axes(time_series, heap_series, dm_series):
    ax = plt.subplot()
    ax.set_xlabel('time')
    ax.set_ylabel('memory in GB')
    ax.plot(time_series,heap_series, color='blue', label='heap memory')
    ax.plot(time_series,dm_series, color='green', label='direct memory')
    ax.legend(loc="upper left")
    # 替换错误的set_xticks调用,传入数值型坐标位置
    ax.set_xticks(range(len(time_series)))
    # 传入字符串标签并设置旋转等样式
    ax.set_xticklabels(time_series, rotation=45, ha='right', fontsize=6)

或者也可以用更简洁的方式拆分样式设置:

def setup_axes(time_series, heap_series, dm_series):
    ax = plt.subplot()
    ax.set_xlabel('time')
    ax.set_ylabel('memory in GB')
    ax.plot(time_series,heap_series, color='blue', label='heap memory')
    ax.plot(time_series,dm_series, color='green', label='direct memory')
    ax.legend(loc="upper left")
    
    ax.set_xticks(range(len(time_series)))
    ax.set_xticklabels(time_series)
    # 单独设置刻度样式
    ax.tick_params(axis='x', rotation=45, ha='right', fontsize=6)

修改后,悬停数据点时就能正常显示X轴的字符串标签,折线图的显示效果也会和第一段代码一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 11:07:11