python matplotlib 问题使其从左到右移动

python matplotlib issue making it to go from left to right

我对 matplotlib 图表有疑问,我一直在尝试多种方法,但似乎无法正常工作,我想要一个从左到右的图表,我的数据如下所示: 价格 = [0.03, 0.025, 0.01, 0.01, 0.05, 0.02] 时间 = ['00:00', '00:05', '00:10', '00:15', '00:20', '00:00'] 我希望图表从左到右,但是当它到达最后一个位置“00:00”时,它又回到了左侧。是否有机会让它在“00:20”之后创建新的刻度“00:00”?下面是代码。

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']

fig, ax = plt.subplots()

plt.title("X")
plt.tick_params(axis='y', which='both', labelleft=False, labelright=True)

plt.plot(prices_time, stored_prices)
plt.grid()
plt.subplots_adjust(left=0.03, right=0.86)
fig.autofmt_xdate()
loc = plticker.MultipleLocator(base=2) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
print(stored_prices, prices_time)
plt.show() #Preview of chart

这是解释我的意思的图片,在“00:20”之后,它不会在“00:20”的右侧创建“00:00”,而是返回到“00:00”,即已经在图的左侧创建:

由于您的 x 值是等距的(最后一个除外),您可以使用任何等距数字序列来绘制它们。是否显示相同距离的最后一个点可能是一个任意决定。

然后你只需要手动设置 x-ticks 并用真实值标记它们:

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 = range(len(prices_time))

fig, ax = plt.subplots()

plt.title("X")
plt.tick_params(axis='y', which='both', labelleft=False, labelright=True)

plt.plot(x, stored_prices)
plt.grid()
plt.subplots_adjust(left=0.03, right=0.86)
fig.autofmt_xdate()
# loc = plticker.MultipleLocator(base=2) 
# this locator puts ticks at regular intervals
# ax.xaxis.set_major_locator(loc)
ax.set_xticks(x)
ax.set_xticklabels(prices_time)

print(stored_prices, prices_time)
plt.show() #Preview of chart