我想在日期执行算术运算,所以我转换了这些日期
idx_1 = 2017-06-07 00:00:00
idx_2 = 2017-07-27 00:00:00
使用浮动,
x1 = time.mktime(idx_1.timetuple()) # returns float of dates
>>> 1496773800.0
x2 = time.mktime(idx_2.timetuple())
>>> 1501093800.0
y1 = 155.98
y2 = 147.07
使用以下代码绘制:
import datetime as dt
import time
import numpy as np
import matplotlib.pyplot as plt
x = [x1, x2]
y = [y1, y2]
Difference = x2 - x1 #this helps to end the plotted line at specific point
coefficients = np.polyfit(x, y, 1)
polynomial = np.poly1d(coefficients)
# the np.linspace lets you set number of data points, line length.
x_axis = np.linspace(x1, x2 + Difference, 3) # linspace(start, end, num)
y_axis = polynomial(x_axis)
plt.plot(x_axis, y_axis)
plt.plot(x[0], y[0], 'go')
plt.plot(x[1], y[1], 'go')
plt.show()
如何让matplotlib在x轴而不是浮点上绘制实际日期?
任何形式的帮助都会受到极大的赞赏。
答案 0 :(得分:1)
从datetime对象开始,您可以使用matplotlib的date2num
和num2date
函数来转换数值和从数值转换。优点是matplotlib.dates
定位器和格式化程序可以理解数值数据。
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates
idx_1 = datetime.datetime(2017,06,07,0,0,0)
idx_2 = datetime.datetime(2017,07,27,0,0,0)
idx = [idx_1, idx_2]
y1 = 155.98
y2 = 147.07
x = matplotlib.dates.date2num(idx)
y = [y1, y2]
Difference = x[1] - x[0] #this helps to end the plotted line at specific point
coefficients = np.polyfit(x, y, 1)
polynomial = np.poly1d(coefficients)
# the np.linspace lets you set number of data points, line length.
x_axis = np.linspace(x[0], x[1] + Difference, 3) # linspace(start, end, num)
y_axis = polynomial(x_axis)
plt.plot(x_axis, y_axis)
plt.plot(x[0], y[0], 'go')
plt.plot(x[1], y[1], 'go')
loc= matplotlib.dates.AutoDateLocator()
plt.gca().xaxis.set_major_locator(loc)
plt.gca().xaxis.set_major_formatter(matplotlib.dates.AutoDateFormatter(loc))
plt.gcf().autofmt_xdate()
plt.show()