You need to enable JavaScript to run this app. Ubuntu下matplotlib绘制x轴为字符串的图表时右下角不显示x坐标如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu下matplotlib绘制x轴为字符串的图表时右下角不显示x坐标如何解决

问题原因

你遇到的是matplotlib 3.1.2版本Linux默认后端的已知bug:当x轴传入字符串类型的分类数据时,状态栏坐标拾取逻辑不会映射分类标签到实际x坐标值,仅显示原始的浮点坐标序号,Windows下默认后端(通常是TkAgg)做了兼容处理因此无异常。

解决方案

给你三个可行方案,按需选择即可:

方案1:将x轴字符串转为datetime类型(最推荐)

matplotlib对时间类型的轴格式化适配最完善,修改后不仅坐标提示正常,未来做轴范围调整、刻度自定义也更方便,修改后代码如下:

import matplotlib.pyplot as plt
from datetime import datetime

x = ["2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04"]
# 转datetime类型
x = [datetime.strptime(d, "%Y-%m-%d") for d in x]
y = [1, 2, 3, 4]
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y)
# 可选:设置x轴日期显示格式,避免显示多余的时分秒
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
plt.show()

运行后状态栏会直接显示对应日期值。

方案2:自定义坐标格式化函数(无需修改原始数据)

如果不想修改原始x轴数据类型,可以重写axes的format_coord方法手动映射坐标到对应标签:

import matplotlib.pyplot as plt

x = ["2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04"]
y = [1, 2, 3, 4]
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y)

# 自定义坐标格式化逻辑
def format_coord(x_val, y_val):
    # 字符串分类x轴的坐标是0、1、2、3的浮点值,四舍五入取索引
    idx = int(round(x_val))
    if 0 <= idx < len(x):
        return f"x={x[idx]}, y={y_val:.4f}"
    return f"x={x_val:.4f}, y={y_val:.4f}"
ax.format_coord = format_coord

plt.show()

方案3:升级matplotlib版本(最简方案)

该bug在matplotlib 3.3.0及以上版本已经修复,如果你可以升级依赖库,直接执行以下命令即可:
pip install --upgrade matplotlib
升级后运行原始代码就能正常显示x轴标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 03:03:01