python 图上的线没有按时间顺序连接每个点

Line on a python graph doesn't connect each point chronologically

我制作了一张图表,其中 x 轴为日期,y 轴为票价,描绘了票价的变化。出于某种原因,连接点的线从第一个点开始,到最后一个点,然后看起来像连接回其他两个点,而不是按时间顺序连接。这似乎是一个很容易解决的问题,但我无法通过查看我的代码来判断我做错了什么,因为我对使用 matplotlib 还是很陌生。这是制作图表的代码片段:

fig, ax = plt.subplots()
ax.xaxis_date()
# Set date format and major locator of x-axis
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m'+ '/' '%d' + '/' '%Y'))
plt.gca().yaxis.set_major_locator(mdates.DayLocator())
graph = fig.add_subplot(111)
xs = [x[0] for x in rows]
ys = [y[1] for y in rows]

plt.plot(xs,ys, 'r-o')
plt.gcf().autofmt_xdate()
graph.set_xticks(xs)
plt.title("Ticket Prices over the course of a month")
plt.xlabel("Date")
plt.ylabel("Ticket Price")  

根据代码,可能是什么导致了问题?该图的图像如下:

如果 xs 未按日期排序,则可能会发生这种情况。 如果这确实是问题所在,您可以通过使用 argsortxsys:

进行排序来解决它
idx = np.argsort(xs)
xs = np.array(xs)[idx]
ys = np.array(ys)[idx]

例如,

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as DT

rows = [(DT.date(2015,9,2), 25),
        (DT.date(2015,9,11), 35),
        (DT.date(2015,9,9), 30),
        (DT.date(2015,9,5), 27),]
fig, ax = plt.subplots()

xs = [x[0] for x in rows]
ys = [y[1] for y in rows]
idx = np.argsort(xs)
xs = np.array(xs)[idx]
ys = np.array(ys)[idx]

plt.plot(xs,ys, 'r-o')
fig.autofmt_xdate()
ax.set_xticks(xs)
ax.xaxis_date()
# Set date format and major locator of x-axis
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
ax.yaxis.set_major_locator(mdates.DayLocator())

plt.title("Ticket Prices over the course of a month")
plt.xlabel("Date")
plt.ylabel("Ticket Price")  
plt.show()

产量


请注意,如果您使用

fig, ax = plt.subplots()

那么你可以用 ax 替换 plt.gca(),因为 plt.gca() returns 当前轴。 同样,您可以将 plt.gcf() 替换为 fig,因为 plt.gcf() returns 当前数字。

您可能不应该调用 graph = fig.add_subplot(111),因为这会在 ax 之上覆盖第二个轴。无需在 graph

上设置刻度线
graph.set_xticks(xs)

以及 ax,因为这会在 x 轴上产生两组刻度线。