Search code examples
pythonmatplotlibpng

matplotlib - xticks in pyplot not set to HH:MM


I am trying to reproduce this example with additional requirements such as title, legends, etc. While some of them seem to be met, the labels aren't appearing at all. I need the x-axis to show HH:MM labels every 30 minutes interval. Can you please help me achieve this?

figtemp, ax = plt.subplots(1, 1, figsize=(9.0, 6.0), dpi=720)
    ax.plot(x1, y1, 'b', linewidth=1)
    xlocator = md.MinuteLocator(interval=30)
    xformatter = md.DateFormatter('%H:%M')
    ax.xaxis.set_major_locator(xlocator)
    ax.xaxis.set_major_formatter(xformatter)
    plt.setp(ax.xaxis.get_majorticklabels(), rotation='vertical', fontsize=9)
    #
    plt.grid(True)
    title = '\n'.join(textwrap.wrap(title, 40))
    plt.title(title, fontsize=12)
    plt.tight_layout(pad=8.0)
    #    
    #plt.plot(x1, y1, 'b', linewidth=1)
    #
    plt.xlabel(axesText[0])
    plt.ylabel(axesText[1])
    #
    #
    if aCondition is True:
        ax.plot(x2, y2, 'r', linewidth=1)
    #
    plt.legend(legends, bbox_to_anchor=[0.0, 0.0], loc='center right')
    #
    plt.savefig('sample.png')
    plt.close()

Solution

  • The x list has timestamp in HH:MM:SS format as a string already because the function passing data to this plot function had done a strftime(). I suppressed that transformation so that the plot function receives a Python date time object.

    Now, it works! yay!

    Please let me know, if I should delete/close this question as obviously, this is not directly related to matplotlib.