Plot x-axis with string array as in the same order in original array and not sort it alphabetically in matplotlib

前端 未结 2 1827
孤街浪徒
孤街浪徒 2021-01-14 02:02

Either Numpy or Matplotlib is changing the order of my np.array and it\'s conflicting with my plot. It\'s causing the months to be out of order while the corresponding data

2条回答
  •  旧巷少年郎
    2021-01-14 02:20

    You will need to use MonthLocator and set_major_locator as shown here: formatting timeseries x-axis in pandas/matplotlib

    Here is my attempt:

    import matplotlib.pyplot as plt
    import numpy as np
    import datetime
    f = np.array([53, 56, 63, 72, 79, 86, 89, 88, 83, 74, 65, 56])
    

    # New stuff:
    from matplotlib.dates import MonthLocator, DateFormatter
    dates = []
    for month in range(1, 13):
        dates.append(datetime.datetime(year=2018, month=month, day=1))
    plt.plot(dates, f)
    ax = plt.gca()
    ax.set_xlim([dates[0], dates[-1]])
    ax.xaxis.set_major_locator(MonthLocator())
    ax.xaxis.set_major_formatter(DateFormatter('%b'))
    

    plt.xlabel('Month')
    plt.ylabel('Temperature')
    plt.title('Average Monthly Temperature in Elizabeth City, NC')
    plt.show()
    

提交回复
热议问题