Python matplotlib中的X tickers与时间作图问题

Python matplotlib中的X tickers与时间作图问题,python,csv,matplotlib,plot,linegraph,Python,Csv,Matplotlib,Plot,Linegraph,我正在尝试编写一个define函数,通过导入的csv文件的数据绘制一个折线图 这是我的一个小样本数据(每分钟的温度读数):- 当我试图将x ticker设置为每小时显示一次时,它们不会显示在绘制的图形中 这是我的密码 df = pd.read_csv(file,names=["time", "temp"]) df["time"]=pd.to_datetime(df["time"]) df=df.set_index('time') df.index = df.index.map (lambda t

我正在尝试编写一个define函数,通过导入的csv文件的数据绘制一个折线图

这是我的一个小样本数据(每分钟的温度读数):-

当我试图将x ticker设置为每小时显示一次时,它们不会显示在绘制的图形中

这是我的密码

df = pd.read_csv(file,names=["time", "temp"])
df["time"]=pd.to_datetime(df["time"])
df=df.set_index('time')
df.index = df.index.map (lambda t: t.strftime('%H:%M'))
print(df)
fig, ax = plt.subplots()
df.plot(ax = ax, color = 'black', linewidth = 0.4, x_compat=True)
ax.set(xlabel='Time (Hour:Minutes)', ylabel='Temperature (Celsius)')
ax.xaxis.set_major_locator(mdates.HourLocator(interval = 1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
fig.autofmt_xdate()
return plt.show()
我尝试过手动标记x标记器

plt.xticks(['0:00', '1:00', '2:00', '3:00', '4:00:0', '5:00', '6:00:0', '7:00', '8:00', '9:00', '10:00'])

这是可行的,但根据官方文件,任何特定的案例都有办法解决

所有绘图函数都希望输入np.array或np.ma.masked_数组。“类似于数组”的类,如pandas数据对象和np.matrix,可能按预期工作,也可能不按预期工作。最好在打印之前将这些对象转换为np.array对象

所以我稍微修改了您的代码(基本上将pd df转换为numpy数组)

df=pd.read\u csv(文件名=[“时间”,“临时”])
df[“time”]=pd.to_datetime(df[“time”])
x_轴=np.数组(df.time.值)
y_轴=np.数组(df.温度值)
图,ax=plt.子批次()
ax.绘图(x_轴,y_轴)
ax.set(xlabel='Time(Hour:Minutes)'、ylabel='Temperature(centrics)')
ax.xaxis.set\u major\u定位器(mdates.HourLocator())
ax.xaxis.set\u major\u格式化程序(mdates.DateFormatter(“%H:%M”))
plt.show()
现在可以看到刻度,如下所示


根据官方文件

所有绘图函数都希望输入np.array或np.ma.masked_数组。“类似于数组”的类,如pandas数据对象和np.matrix,可能按预期工作,也可能不按预期工作。最好在打印之前将这些对象转换为np.array对象

所以我稍微修改了您的代码(基本上将pd df转换为numpy数组)

df=pd.read\u csv(文件名=[“时间”,“临时”])
df[“time”]=pd.to_datetime(df[“time”])
x_轴=np.数组(df.time.值)
y_轴=np.数组(df.温度值)
图,ax=plt.子批次()
ax.绘图(x_轴,y_轴)
ax.set(xlabel='Time(Hour:Minutes)'、ylabel='Temperature(centrics)')
ax.xaxis.set\u major\u定位器(mdates.HourLocator())
ax.xaxis.set\u major\u格式化程序(mdates.DateFormatter(“%H:%M”))
plt.show()
现在可以看到刻度,如下所示

plt.xticks(['0:00', '1:00', '2:00', '3:00', '4:00:0', '5:00', '6:00:0', '7:00', '8:00', '9:00', '10:00'])