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

matplotlib折线图x轴重复时间标签回跳 如何新增右侧独立刻度

问题原因

你直接传入字符串类型的时间列表作为plot()的x轴参数时,matplotlib会将相同内容的字符串识别为同一个刻度位置,所以最后一个'00:00'会匹配到第一个出现的同名字符串的x轴位置,导致折线回跳。

解决方案

用连续的数字索引作为实际的x轴坐标绘制折线,再手动将x轴刻度标签替换为你需要的时间字符串即可,修改后的代码如下:

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

stored_prices = [0.03, 0.025, 0.01, 0.01, 0.05, 0.02]
prices_time = ['00:00', '00:05', '00:10', '00:15', '00:20', '00:00']
# 生成连续索引作为x轴实际坐标,保证顺序和列表顺序一致
x_index = range(len(prices_time))

fig, ax = plt.subplots()

plt.title("X")
plt.tick_params(axis='y', which='both', labelleft=False, labelright=True)
# 用索引作为x值绘图,不会出现同名字符串匹配导致的位置偏移
plt.plot(x_index, stored_prices)
# 手动替换x轴刻度标签为时间字符串
plt.xticks(x_index, prices_time)
plt.grid()
plt.subplots_adjust(left=0.03, right=0.86)
fig.autofmt_xdate()
loc = plticker.MultipleLocator(base=2)
ax.xaxis.set_major_locator(loc)
print(stored_prices, prices_time)
plt.show()
效果说明

修改后x轴会按照索引顺序从左到右排列6个独立位置,第6个位置的标签会独立显示为'00:00',位于'00:20'右侧,折线会按照数据输入顺序正常绘制,不会出现回跳问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:06:02