plot_date function set xticks for hourly data

感情迁移 提交于 2021-01-29 07:08:42

问题


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.

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()


回答1:


Use matplotlib.dates.DateFormatter. First import it at the top

import matplotlib.dates as mdates

then replace this line

fig = plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=5))

by something like this

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



来源:https://stackoverflow.com/questions/52729169/plot-date-function-set-xticks-for-hourly-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!