问题描述
我目前有一个功能,可以根据MM-DD-YYYY HH-MM格式的时间/日期数据创建时间序列图.我不确定如何更改x轴刻度,以便它显示小时以及日期,因为它当前仅显示日期.
I currently have a function that creates a time series graph from time/date data that is in MM-DD-YYYY HH-MM format. I am unsure as to how to change the x axis ticks such that it displays hours as well as the date as it currently only shows dates.
即使我已指定hour_locator且数据为每小时,但我包含的set_major_locator行仅返回具有年份的刻度线.
The set_major_locator line I included only returns ticks that have the year even though I have specified the hour_locator and the data is hourly.
def graph(region):
fig = plt.figure(num=None, figsize=(60, 20), dpi=100, facecolor='w', edgecolor='k')
df_da_region = df_da_abv_09[df_da_abv_09['Settlement Point'] == region]
df_rt_region = df_rt_abv_09[df_rt_abv_09['Settlement Point Name'] == region]
fig = plt.plot_date(x=list(df_da_region['DateTime']), y=list(df_da_region['Settlement Point Price']), xdate = True, fmt="r-", linewidth=0.7)
fig = plt.plot_date(x=list(df_rt_region['DateTime']), y=list(df_rt_region['Settlement Point Price']), xdate = True, fmt="g-", alpha=0.5, linewidth=0.7)
fig = plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=5))
plt.show()
推荐答案
使用 matplotlib.dates.DateFormatter
.首先将其导入顶部
Use matplotlib.dates.DateFormatter
. First import it at the top
import matplotlib.dates as mdates
然后替换此行
通过这样的东西
myFmt = mdates.DateFormatter('%y-%m-%d %H') # here you can format your datetick labels as desired
plt.gca().xaxis.set_major_formatter(myFmt)
在一个带有随机数的示例中(因为您没有提供示例数据),看起来像这样
In a example with random numbers (since you haven't provided sample data), it looks like this
在这里,可以根据需要选择格式化程序:日期+小时.有关如何在轴上设置日期格式的更多信息,请检查这里
Here, the formatter is chosen as you wanted: dates + hours. For further info about how to format the date on the axis, check here
这篇关于plot_date函数为小时数据设置xticks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!