【问题标题】:plot_date function set xticks for hourly dataplot_date 函数为每小时数据设置 xticks
【发布时间】:2019-03-14 17:06:10
【问题描述】:

我目前有一个函数可以从 MM-DD-YYYY HH-MM 格式的时间/日期数据创建时间序列图。我不确定如何更改 x 轴刻度,使其显示小时和日期,因为它目前只显示日期。

我包含的 set_major_locator 行仅返回具有年份的刻度,即使我指定了 hour_locator 并且数据是每小时的。

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

【问题讨论】:

  • minimal reproducible example 在这里很有用。
  • 我添加了一张图片并删除了几行不相关的代码。
  • 如果没有可运行的代码,我无法给出完整的解决方案。所以只是为了让你走上正确的轨道:需要设置刻度的格式化程序以与定位器一起使用。如果您更改定位器,您需要通知格式化程序,或者,因为这不是显而易见的,所以也设置一个新的格式化程序。

标签: python datetime matplotlib plot


【解决方案1】:

使用matplotlib.dates.DateFormatter。先在顶部导入

import matplotlib.dates as mdates

然后替换这一行

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

通过这样的方式

myFmt = mdates.DateFormatter('%y-%m-%d %H') # here you can format your datetick labels as desired
plt.gca().xaxis.set_major_formatter(myFmt)

在一个带有随机数的示例中(因为您没有提供示例数据),它看起来像这样

在这里,可以根据需要选择格式化程序:日期 + 小时。有关如何在轴上格式化日期的更多信息,请查看here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多