如何在使用matplotlib时在X轴上显示年份?

时间:2017-06-06 08:16:23

标签: python arrays matplotlib

我从未使用过python,我必须这样做才能成为我的第一个任务。我花了3个小时才到达这一点,我真的需要一些帮助。

我有一个带有一些数字的一维数组。我必须制作一个时间序图。

import datetime
import matplotlib.pyplot as plt
import numpy as np

data = np.load("abnormal.npy")

x = np.array(range(1,len(data)+1))
y = np.load("abnormal.npy")

plt.plot(x,y)
plt.show()    

plot

正如您所见,X轴现在是我的数组的数组范围。 如何将此更改为2002-2012的日期时间?

2 个答案:

答案 0 :(得分:1)

您需要一个与数据数组完全一样的日期数组。如果是你知道每天有一个数据点,你可以创建这个数组

start = datetime.date(2002, 01, 01)
dates = [start + datetime.timedelta(n) for n in range(len(y))]

完整示例:

import datetime
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

y = np.cumsum(np.random.normal(size=4000))

start = datetime.date(2002, 01, 01)
dates = [start + datetime.timedelta(n) for n in range(len(y))]

plt.plot(dates,y)
plt.show() 

enter image description here

答案 1 :(得分:0)

你喜欢这样做,

import pandas as pd

y_len = 100
x = pd.date_range("20020101", freq='D', periods=y_len).strftime("%Y-%m-%d").tolist()

你只需要获得Y轴的长度并指向y_len,为你提问

y_len = len(data)

示例代码输出是,

['2002-01-01', '2002-01-02', '2002-01-03', '2002-01-04', '2002-01-05', '2002-01-06', '2002-01-07', '2002-01-08', '2002-01-09', '2002-01-10', '2002-01-11', '2002-01-12', '2002-01-13', '2002-01-14', '2002-01-15', '2002-01-16', '2002-01-17', '2002-01-18', '2002-01-19', '2002-01-20', '2002-01-21', '2002-01-22', '2002-01-23', '2002-01-24', '2002-01-25', '2002-01-26', '2002-01-27', '2002-01-28', '2002-01-29', '2002-01-30', '2002-01-31', '2002-02-01', '2002-02-02', '2002-02-03', '2002-02-04', '2002-02-05', '2002-02-06', '2002-02-07', '2002-02-08', '2002-02-09', '2002-02-10', '2002-02-11', '2002-02-12', '2002-02-13', '2002-02-14', '2002-02-15', '2002-02-16', '2002-02-17', '2002-02-18', '2002-02-19', '2002-02-20', '2002-02-21', '2002-02-22', '2002-02-23', '2002-02-24', '2002-02-25', '2002-02-26', '2002-02-27', '2002-02-28', '2002-03-01', '2002-03-02', '2002-03-03', '2002-03-04', '2002-03-05', '2002-03-06', '2002-03-07', '2002-03-08', '2002-03-09', '2002-03-10', '2002-03-11', '2002-03-12', '2002-03-13', '2002-03-14', '2002-03-15', '2002-03-16', '2002-03-17', '2002-03-18', '2002-03-19', '2002-03-20', '2002-03-21', '2002-03-22', '2002-03-23', '2002-03-24', '2002-03-25', '2002-03-26', '2002-03-27', '2002-03-28', '2002-03-29', '2002-03-30', '2002-03-31', '2002-04-01', '2002-04-02', '2002-04-03', '2002-04-04', '2002-04-05', '2002-04-06', '2002-04-07', '2002-04-08', '2002-04-09', '2002-04-10']