【问题标题】:Setting the x axis as time (years, months) for a set of values将 x 轴设置为一组值的时间(年、月)
【发布时间】:2015-05-11 00:23:08
【问题描述】:

我有一组对应于一个月和一年(2012 年 1 月、2012 年 3 月、2012 年 10 月到 2014 年)的值,我试图绘制每个月的值,但是当我运行脚本时 x轴被分配为'1、2、3'等

import numpy as np
import matplotlib.pyplot as plt
plt.plot([10, 180, 153, 80, 11, 92, 201, 74, 24])
plt.ylabel('Value')
plt.xlabel('Time')
plt.title('Number over time')
plt.show()
plt.ylim([0,300])
plt.show()

如何将 X 轴设置为这些特定月份或 2011-2014 年的所有月份?

我发现 matplotlib 中的演示图非常令人困惑 http://matplotlib.org/examples/pylab_examples/date_demo1.html

【问题讨论】:

    标签: python numpy time graph plot


    【解决方案1】:

    您实际上从未向 mpl 发送任何日期。它不知道您正在尝试在 x 轴上绘制日期:

    import numpy as np
    import matplotlib.pyplot as plt
    import datetime as dt
    
    dates = []
    for year in range(2012, 2014):
        for month in range(1, 12):
            dates.append(dt.datetime(year=year, month=month, day=1))
    
    y = [10, 180, 153, 80, 11, 92, 201, 74, 24]
    plt.plot(dates[:9], y)
    plt.show()
    

    此示例仅绘制前 9 个月,因为这是您要绘制的示例列表的长度。如果您想要特定日期,只需通过 datetime 模块自己声明即可。 IE。你的日期[0] 看起来像:

    datetime.datetime(2012, 1, 1, 0, 0) 
                     #year, month, day, hour min if I recall correctly.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-04
      • 2021-08-15
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2021-03-18
      相关资源
      最近更新 更多